Cách ghi file trong Java sử dụng FileOutputStream

Trong Java, FileOutputStream là class thuộc luồng bytes (bytes stream) được sử dụng để xử lý dữ liệu nhị phân. Để ghi dữ liệu vào file, bạn phải chuyển dữ liệu sang byte rồi mới lưu vào file.

Ví dụ ghi file trong Java sử dụng FileOutputStream

package com.ngockhuong;

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 = "Nội dung cần ghi";

		try {

			file = new File("data.txt");
			fop = new FileOutputStream(file);

			// kiểm tra nếu file chưa tồn tại thì tạo mới
			if (!file.exists()) {
				file.createNewFile();
			}

			// chuyển nội dung sang một mảng byte
			byte[] contentInBytes = content.getBytes();

			fop.write(contentInBytes);
			fop.flush();
			fop.close();

			System.out.println("Xong");

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (fop != null) {
					fop.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

Trong Java 7, bạn có thể sử dụng cấu trúc lệnh “try resource close” để xử lý ngắn gọn hơn

package com.ngockhuong;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class WriteFileExample {
	public static void main(String[] args) {

		File file = new File("data.txt");
		String content = "Nội dung cần ghi vào file";

		try (FileOutputStream fop = new FileOutputStream(file)) {
			// nếu file chưa có thì tạo mới
			if (!file.exists()) {
				file.createNewFile();
			}

			// chuyển nội dung sang một mảng byte
			byte[] contentInBytes = content.getBytes();

			fop.write(contentInBytes);
			fop.flush();
			// FileOutputStream sẽ tự động được đóng khi dùng "try resource close"
			// fop.close();

			System.out.println("Done");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

Tham khảo

  1. FileOutputStream Java Doc
  2. Cấu trúc lệnh try-with-resources

0 0 votes
Đánh giá bài viết
Nhận thông báo
Thông báo khi có
guest

0 Bình luận
Phản hồi nội tuyến
Xem tất cả các bình luận