Viết nội dung vào file trong java

Bài trước tôi đã hướng dẫn cách tạo file trong java.Bài viết này hướng dẫn các bạn cách để viết nội dung vào một file.Trong Java, bạn có thể sử dụng java.io.BufferedWriter để làm được điều đó.

1. Dùng cách cổ điển BufferedWriter

Ví dụ về BufferedWriter để viết nội dung vào một file, tạo ra các file nếu không tồn tại, các nội dung hiện có sẽ được ghi đè.

WriteToFileExample1.java

package com.itphutran;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class WriteToFileExample1 {

	private static final String FILENAME = "E:\\test\\filename.txt";

	public static void main(String[] args) {

		BufferedWriter bw = null;
		FileWriter fw = null;

		try {

			String content = "This is the content to write into file\n";

			fw = new FileWriter(FILENAME);
			bw = new BufferedWriter(fw);
			bw.write(content);

			System.out.println("Done");

		} catch (IOException e) {

			e.printStackTrace();

		} finally {

			try {

				if (bw != null)
					bw.close();

				if (fw != null)
					fw.close();

			} catch (IOException ex) {

				ex.printStackTrace();

			}

		}

	}

}

Output: Một file mới được tạo ra với các nội dung sau đây:

E: \\ \\ test filename.txt
This is the content to write into file

2. Ví dụ JDK7

try-with-resources ví dụ để tự động đóng các tập tin.

WriteToFileExample2.java

package com.itphutran;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class WriteToFileExample2 {

	private static final String FILENAME = "E:\\test\\filename.txt";

	public static void main(String[] args) {

		try (BufferedWriter bw = new BufferedWriter(new FileWriter(FILENAME))) {

			String content = "This is the content to write into file\n";

			bw.write(content);

			// no need to close it.
			//bw.close();

			System.out.println("Done");

		} catch (IOException e) {

			e.printStackTrace();

		}

	}

}

 

3. BufferedWriter – Append

// append to end of file
FileWriter fw = new FileWriter(FILENAME, true);
BufferedWriter bw = new BufferedWriter(fw);

 

 

x