Java写入目录只会创建文件

时间:2012-03-29 02:33:13

标签: java file file-io filewriter bufferedwriter

我正在为我玩的游戏开发一个项目,我似乎无法正确地写入文件。我让它在某一点上工作,但改变了几件事,并将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和,是的)我从这里得到了其他问题。我认为这可能是问题所在,但在将它们评论出来并将items.xml直接写入我的项目文件夹之后,它仍然是空的。 我尝试添加一些输出用于调试目的,我得到的正是我的预期。所有变量输出都符合它们的要求。

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

关于我做错了什么想法?

1 个答案:

答案 0 :(得分: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,因此您不太可能只有一个根元素。