0

我正在为我玩的游戏开发一个项目,但我似乎无法让它正确写入文件。我曾经让它工作过,但改变了几件事,并将 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 和 ,true) 我从这里的其他问题中得到。我认为这可能是问题所在,但是在将它们注释掉并将 items.xml 直接写入我的项目文件夹之后,它仍然是空的。我尝试添加一些输出以进行调试,结果完全符合我的预期。所有变量输出都匹配它们应该的。

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

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

4

1 回答 1

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,因此您不太可能只得到一个根元素。

于 2012-03-29T02:35:06.120 回答