2015-09-30 06:30:02
阅读( 1927 )
当要写文本文件时最好使用Writer类,而不是直接写OutputStream;因为Writer类就是为写文本而设计的。
使用BufferedWriter写入文本时不用讲文本转换成字节数组。在下面的示例代码中我们向文件中写入两行文本。
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
/**
*
* @author outofmemory.cn
*/
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().
分享给朋友:
亲~ 如果您有更好的答案 可在评论区发表您独到的见解。
您想查看更多的信息:
面试题