我试图写入一个文本文件,但即使该方法创建该文件,如果它不存在,它不会写.我已经通过其他几个有类似问题的帖子,并按照建议但没有运气.
通过使用调试器,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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
Jon*_*eet 17
知道了 - 这就是问题所在:
new FileWriter(bookingFile.getName(),true);
Run Code Online (Sandbox Code Playgroud)
该getName()方法将返回bookinginfo.txt,这意味着它将创建一个bookinginfo.txt在当前工作目录中调用的文件.
只需使用以下构造函数File:
fw = new FileWriter(bookingFile, true);
Run Code Online (Sandbox Code Playgroud)
另请注意,您不需要先调用createNewFile()- FileWriter如果文件不存在,构造函数将创建该文件.
另外,我个人不喜欢FileWriter它 - 它总是使用平台默认编码.我建议使用FileOutputStream包装在OutputStreamWriter可以指定编码的位置.或者使用Guava辅助方法,使所有这些方法更简单.例如:
Files.append(bookingFile, data, Charsets.UTF_8);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4227 次 |
| 最近记录: |