第1个回答 2015-11-04
使用BufferedWriter写入文本时不用将文本转换成字节数组,直接整行整行的写入,大大提供了写入效率。
在下面的示例代码中向文件中写入两行文本。
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
/**
*
* @author gdb
*/
public class Main {
/**
* Prints some data to a file using a BufferedWriter
*/
public void writeToFile(String filename) {
BufferedWriter bufferedWriter = null;
try {
//Construct the BufferedWriter object
bufferedWriter = new BufferedWriter(new FileWriter(filename));
//Start writing to the output stream
bufferedWriter.write("Writing line one to file");
bufferedWriter.newLine();
bufferedWriter.write("Writing line two to file");
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
//Close the BufferedWriter
try {
if (bufferedWriter != null) {
bufferedWriter.flush();
bufferedWriter.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new Main().writeToFile("myFile.txt");
}
}
执行上述代码后文件中的文本如下:
Writing line one to file
Writing line two to file
注意使用BufferedWriter一定要在finally中flush()并close().