gpt4 book ai didi

Java写入目录只会创建文件

转载 作者:行者123 更新时间:2023-12-01 15:28:10 25 4
gpt4 key购买 nike

我正在为我玩的游戏开发一个项目,但我似乎无法让它正确写入文件。我曾经让它工作过,但改变了一些事情,并将 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 直接写入我的项目文件夹后,它仍然是空的。我尝试添加一些输出用于调试目的,并且得到了我所期望的结果。所有变量输出都符合其应有的内容。

该文件已在正确的文件夹中创建,但未向其中写入任何内容。

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

最佳答案

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

添加:

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,因此最终不太可能只有一个根元素。

关于Java写入目录只会创建文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9918351/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com