【发布时间】:2013-12-03 23:41:05
【问题描述】:
我目前在我的代码中写入文本文件时遇到问题,整个程序都被命中,所有内容都将打印到控制台。没有错误。但是文件是空的。有什么建议吗?
public textFiles(String filePath)
{
File file = new File(filePath);
try{
fstream = new FileWriter(filePath,true);
}
catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
out = new BufferedWriter(fstream);
System.out.println("try");
addToText("WOOOOHOOO");
System.out.println(file.exists());
}
public void addToText(String Line)
{
try {
out.write(Line);
out.newLine();
} catch (IOException e) {
System.err.println("writing Error");
}
System.out.println("SHOULDA F****** WORKED");
}
【问题讨论】:
-
你要关闭作者吗?
-
您没有关闭编写器,您的代码不完整且有错误。
-
写在 try 子句中。在创建异常的情况下编写是没有意义的。还有a simpler way:
Files.write(Paths.get(file.getName()), content.getBytes());。 -
感谢 cmets。我的代码没有错误木马。原来是因为我没有关闭作者。