Java – BufferedWriter

如果您想使用BufferedWriter将某些内容写入 Java 中的文件中,请使用以下代码作为模板,并按自己的方式重复使用它。

1)使用不带try-with-resourcesBufferedWriter(在 Java 7 之前)

package com.howtodoinjava.examples.io;

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

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

			String content = "Hello Learner !! Welcome to howtodoinjava.com.";

			File file = new File("c:/temp/samplefile.txt");

			FileWriter fw = new FileWriter(file);
			BufferedWriter bw = new BufferedWriter(fw);

			bw.write(content);
			bw.close();

		} 
		catch (IOException e) 
		{
			e.printStackTrace();
		}
	}
}

2)将BufferedWritertry-with-resources结合使用(Java 7 及更高版本)

package com.howtodoinjava.examples.io;

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

public class BufferedWriterExample 
{
	public static void main(String[] args)
	{
		try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("C:\\temp\\testOut.txt")))
		{

			String content = "Hello Learner !! Welcome to howtodoinjava.com.";

			bufferedWriter.write(content);

		} 
		catch (IOException e) 
		{
			e.printStackTrace();
		}
	}
}