我正在尝试写入文本文件,但即使该方法创建该文件(如果该文件不存在),也不会写入。我已经通过其他几个有类似问题的帖子并遵循了建议,但没有运气。
通过使用调试器,String数据包含应该写入的正确数据,但它永远不会写入文本文件。
对于我忽略的事情的任何建议都将不胜感激。
private static void createReservation(String filmName, String date, int noOfSeats, String username) {
FileWriter fw = null;
try {
File bookingFile = new File("C:\\server\\bookinginfo.txt");
if (!bookingFile.exists())
{
bookingFile.createNewFile();
}
fw = new FileWriter(bookingFile.getName(),true);
String data = "<"+filmName+"><"+date+"><"+Integer.toString(noOfSeats)+"><"+username+">\r\n";
fw.write(data);
fw.flush();
} catch (IOException ex) {
Logger.getLogger(FilmInfoHandler.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
fw.close();
} catch (IOException ex) {
Logger.getLogger(FilmInfoHandler.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
答案 0 :(得分:17)
知道了 - 这就是问题所在:
new FileWriter(bookingFile.getName(),true);
getName()
方法只返回bookinginfo.txt
,这意味着它将在当前工作目录中创建名为bookinginfo.txt
的文件。
只需使用带File
的构造函数:
fw = new FileWriter(bookingFile, true);
另请注意,您无需先调用createNewFile()
- 如果文件不存在,FileWriter
构造函数将创建该文件。
顺便说一句,我个人不是FileWriter
的粉丝 - 总是使用平台默认编码。我建议使用包含在FileOutputStream
中的OutputStreamWriter
,您可以在其中指定编码。或者使用Guava辅助方法,使所有这些方法更简单。例如:
Files.append(bookingFile, data, Charsets.UTF_8);
答案 1 :(得分:1)
使用此
fw = new FileWriter(bookingFile.getAbsolutePath(),true);
而不是
fw = new FileWriter(bookingFile.getName(),true);