【问题标题】:Why won't PrintWriter Write to a Dynamically Created Text File为什么 PrintWriter 不写入动态创建的文本文件
【发布时间】:2017-11-10 02:47:36
【问题描述】:

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

【问题讨论】:

    标签: java io printwriter


    【解决方案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--");
    

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

    【讨论】:

      【解决方案2】:

      在处理可能导致异常的事情时,请始终记住使用 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();
          }
      

      【讨论】:

      • exists() 测试和createNewFile() 在它们所在的地方或其他任何地方都是徒劳的。
      • @EJP 但是如果他们出于某种原因使用BufferedWriter 怎么办,是否有必要按照我的方式创建一个新文件?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-17
      相关资源
      最近更新 更多