为什么没有PrintWriter写入动态创建的文本文件

时间:2017-11-10 02:47:36

标签: java io printwriter

所以我正在制作游戏并尝试添加一个高分表,用于读取文本文件中的某些数据。如果用户之前从未玩过游戏或文件尚不存在,则动态创建文本文件。我可以成功创建此文件,但由于某种原因,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

2 个答案:

答案 0 :(得分:1)

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--");

所以这些代码都没有执行过。

答案 1 :(得分:-1)

在处理可能导致异常的事情时,请始终记住使用try / catch语句。那是一个问题。 之后,该文件仍然没有写入。你要做的就是让printwriters在!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();
    }