[英]Why won't PrintWriter Write to a Dynamically Created Text File
因此,我正在做一个游戏,并尝试添加一个高分表,该表读取文本文件中的某些数据。 如果用户之前从未玩过游戏或该文件不存在,则会动态创建该文本文件。 我可以成功创建此文件,但是由于某些原因,PrintWriter不会写入该文件。 有人可以解释为什么吗?
//VARIABLE DECLARATIONS
String currentDirectory = System.getProperty("user.dir"); //Contains the current directory the program is located in.
File forTable = new File(currentDirectory + "\\highScoreTable.txt");
PrintWriter updateTable = new PrintWriter(new FileWriter(forTable), true);
if(!forTable.exists())
{
forTable.createNewFile();
updateTable.println("Player\t\tScore");
updateTable.println("-------\t\t--");
updateTable.println("-------\t\t--");
updateTable.println("-------\t\t--");
updateTable.println("-------\t\t--");
updateTable.println("-------\t\t--");
}
updateTable.close(); //Close the print writer
PrintWriter updateTable = new PrintWriter(new FileWriter(forTable), true);
if(!forTable.exists())
在这一点上,这个测试不可能是正确的。 您刚刚使用new FileWriter(...)
创建了文件。 它存在。
forTable.createNewFile();
为此,为时已晚,您再也不需要与new FileWriter(...)
关联。 构造FileWriter
会创建文件。
updateTable.println("Player\t\tScore");
updateTable.println("-------\t\t--");
updateTable.println("-------\t\t--");
updateTable.println("-------\t\t--");
updateTable.println("-------\t\t--");
updateTable.println("-------\t\t--");
因此,这些代码都没有执行过。
处理可能导致异常的事物时,请始终记住使用try / catch语句。 那是一个问题。 之后,该文件仍然不会写入。 您要做的是将!forTable.Exists()
书写调用放在!forTable.Exists()
部分之外。 这是您的代码的预期修订版本。
String currentDirectory = System.getProperty("user.dir"); //Contains the
current directory the program is located in.
File forTable = new File(currentDirectory + "\\highScoreTable.txt");
System.out.println(currentDirectory);
try {
PrintWriter updateTable = new PrintWriter(new FileWriter(forTable), true);
if(!forTable.exists())
{
forTable.createNewFile();
}
updateTable.println("Player\t\tScore");
updateTable.println("-------\t\t--");
updateTable.println("-------\t\t--");
updateTable.println("-------\t\t--");
updateTable.println("-------\t\t--");
updateTable.println("-------\t\t--");
updateTable.close(); //Close the print writer
}catch(IOException e) {
e.printStackTrace();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.