【问题标题】:Java writing to directory only creates fileJava写入目录只创建文件
【发布时间】:2012-04-12 16:26:38
【问题描述】:

我正在为我玩的游戏开发一个项目,但我似乎无法让它正确写入文件。我曾经让它工作过,但改变了几件事,并将 write 方法移到了另一个类中。在这个过程中的某个地方,我一定是弄坏了一些东西。

public static void write(item a) {
    //Variable declaration. outp is private instance String array
    outp[0] = "<" + a.getID() + ">\n";
    outp[1] = "<name>" + a.getName() + "</name>";
    outp[2] = "<description>" + a.getDesc() + "</description>\n";
    outp[3] = "<type>" + a.getType() + "</type>\n";
    outp[4] = a.getOtherCode() + "\n";
    outp[5] = "</" + a.getID() + ">\n";
    try{
    //Create/Append data to items.xml located in variable folder.
    FileWriter writeItem = new FileWriter(modTest.modName + File.separator +"items.xml", true); 
    BufferedWriter out = new BufferedWriter(writeItem);

    //Loop through array and write everything
    for(int i = 0; i < outp.length; i++) {
        System.out.println("outp[" + i + "] = " + outp[i]);
        System.out.println("Writing line " + i + " of item "+  a.getID());
        out.write(outp[i]); 
    }

    }catch (Exception e) { System.err.println("Erro: " + e.getMessage()); 
    }
}

//File.seperator and ,true) 我从这里的其他问题中得到。我认为这可能是问题所在,但是在将它们注释掉并将 items.xml 直接写入我的项目文件夹之后,它仍然是空的。 我尝试添加一些输出以进行调试,结果完全符合我的预期。所有变量输出都匹配它们应该的。

文件在正确的文件夹中创建,但没有写入任何内容。

关于我做错了什么有什么想法吗?

【问题讨论】:

    标签: java file file-io filewriter bufferedwriter


    【解决方案1】:

    您需要关闭文件描述符,以便将内容刷新到磁盘。

    添加:

    out.close();
    

    这样你的方法就变成了:

    public static void write(item a) {
      //Variable declaration. outp is private instance String array
      outp[0] = "<" + a.getID() + ">\n";
      outp[1] = "<name>" + a.getName() + "</name>";
      outp[2] = "<description>" + a.getDesc() + "</description>\n";
      outp[3] = "<type>" + a.getType() + "</type>\n";
      outp[4] = a.getOtherCode() + "\n";
      outp[5] = "</" + a.getID() + ">\n";
    
      try {
        //Create/Append data to items.xml located in variable folder.
    
        FileWriter writeItem = new FileWriter(modTest.modName + File.separator +"items.xml", true); 
        BufferedWriter out = new BufferedWriter(writeItem);
    
        //Loop through array and write everything 
    
        for(int i = 0; i < outp.length; i++) {
          System.out.println("outp[" + i + "] = " + outp[i]);
          System.out.println("Writing line " + i + " of item "+  a.getID());
          out.write(outp[i]); 
        }
    
        out.close();
      }
      catch (Exception e) { System.err.println("Erro: " + e.getMessage()); }
    }
    

    如果不调用close(),您将泄漏文件描述符,并且在足够长的时间后,您将无法打开更多文件进行写入。

    还请注意,每次写入文件时,您都追加到文件中(而不是每次都将其截断并从头开始)。由于您正在向其写入 XML,因此您最终不太可能只有一个根元素。

    【讨论】:

    • +1 表示一针见血。我唯一的抱怨:我喜欢早上泄露文件描述符的味道......
    • 是的,这就是我(再次)忘记的。感谢您额外的一双眼睛。
    猜你喜欢
    • 2020-11-23
    • 1970-01-01
    • 2021-03-10
    • 2012-11-12
    • 1970-01-01
    • 2014-10-06
    • 1970-01-01
    • 1970-01-01
    • 2017-12-01
    相关资源
    最近更新 更多