我想创建一个包含一些文本的简单文本文件。
import java.io.*;
class TextFileWriter{
public static void writeTextFile(String fileName, String s) {
FileWriter output = null;
try {
output = new FileWriter(fileName);
BufferedWriter writer = new BufferedWriter(output);
writer.write(s);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
}
}
}
}
public static void main(String args[]){
writeTextFile("myText.txt","some text");
}
}
当我运行此代码时,我成功创建了文本文件,但是当我打开它时,我看不到内容("一些文字")。我究竟做错了什么?
答案 0 :(得分:5)
您正在关闭基础FileWriter
,但实际数据仍然存储(缓存)在BufferedWriter
对象中。这是你必须关闭的对象:
FileWriter output = new FileWriter(fileName);
BufferedWriter writer = new BufferedWriter(output);
writer.write(s);
writer.flush(); // Good practice but not required
writer.close();