Bài viết này, tôi sẽ hướng dẫn các bạn cách ghi dữ liệu vào file trong Java sử dụng FileOutputStream, Trong Java, FileOutputStream là một lớp nằm trong gói java.io.
Trước đó chúng ta đã biết cách đọc một file trong java . Trong hướng dẫn này chúng ta sẽ biết cách làm thế nào để ghi vào file trong java sử dụng FileOutputStream
. Tôi sẽ sử dụng phương thức write() của FileOutputStream
để viết nội dung vào một file. Dưới đây là phương thức của write:
Public void write ( byte [] b ) throws IOException
Nó viết các b.length
với b truyền vào một mảng byte được chỉ định vào luồng đầu ra tập tin này. Như các bạn có thể thấy phương pháp này cần có một mảng các byte để ghi chúng vào một file. Do đó, chúng ta cần phải chuyển đổi nội dung của chúng ta thành mảng byte trước khi ghi nó ghi vào file.
Ghi dữ liệu vào file trong Java sử dụng FileOutputStream
package com.itphutran.file; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; public class WriteFileExample { public static void main(String[] args) { FileOutputStream fop = null; File file; String content = "This is the text content"; try { file = new File("c:/newfile.txt"); fop = new FileOutputStream(file); // if file doesnt exists, then create it if (!file.exists()) { file.createNewFile(); } // get the content in bytes byte[] contentInBytes = content.getBytes(); fop.write(contentInBytes); fop.flush(); fop.close(); System.out.println("Done"); } catch (IOException e) { e.printStackTrace(); } finally { try { if (fop != null) { fop.close(); } } catch (IOException e) { e.printStackTrace(); } } } }
Kết quả:
Viết file xong!
Mở file để xem:
Ví dụ về JDK7 được cập nhật, sử dụng phương pháp “try resource close” để xử lý file dễ dàng.
Tạo file WriteFileExample2
package com.itphutran.file; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; public class WriteFileExample2 { public static void main(String[] args) { File file = new File("E:\\project\\huongdanjava\\javaio\\writeFile.txt"); String content = "Chieu chieu ra dung bo song\nKhong thay co be toi yeu ngay nao!"; try (FileOutputStream fop = new FileOutputStream(file)) { // if file doesn't exists, then create it if (!file.exists()) { file.createNewFile(); } // get the content in bytes byte[] contentInBytes = content.getBytes(); fop.write(contentInBytes); fop.flush(); fop.close(); System.out.println("Done"); } catch (IOException e) { e.printStackTrace(); } } }
Kết quả cũng tương tự như trên:
Done!
Mở file để xem:
#Tổng kết
Như vậy, qua bài này tôi đã trình bày các bạn cách để viết file sử dụng FileOutputStream trong Java. Các bạn cần ôn thực hiện cho tốt và biết cách xử lý. Vì phần file là một trong những phần thường xuyên sử dụng trong các ứng dụng.