如何在 Java 中多次调用格式化?
为了简单起见,我有一个名为 FileEditor 的类: 软件包 modmaker;
import java.io.FileNotFoundException;
import java.util.*;
public class FileEditor {
public static Formatter projectFile;
public static String modName;
public void overWriteFile(){
try {
projectFile = new Formatter(modName+".txt");
System.out.println("Wrote project file");
} catch (FileNotFoundException e) {
System.out.println("Error writing project file");
}
}
public void addBlock(){
projectFile.format("blocks "+Blocks.blockName+" "+Blocks.blockDisplayName+" "+Blocks.doesEmitLight+" "+Blocks.lightValue+" "+Blocks.doesGenNaturally+" "+Blocks.genBelowLevel+" "+Blocks.genRariety+" "+Blocks.genClump+" "+Blocks.blockTexturePath);
projectFile.close();
}
}
当用户第一次进入程序时,会调用overWriteFile方法,制作文件。然后用户进入另一个窗口,在其中定义 block.* 变量,然后当调用按钮上的 actionPerformed 时,我希望调用 addBlock() ,使用当前变量格式化文件,但是当我尝试执行以下操作时这多次,我给了我控制台错误......请帮忙。
To make it simple, I have a class called FileEditor:
package modmaker;
import java.io.FileNotFoundException;
import java.util.*;
public class FileEditor {
public static Formatter projectFile;
public static String modName;
public void overWriteFile(){
try {
projectFile = new Formatter(modName+".txt");
System.out.println("Wrote project file");
} catch (FileNotFoundException e) {
System.out.println("Error writing project file");
}
}
public void addBlock(){
projectFile.format("blocks "+Blocks.blockName+" "+Blocks.blockDisplayName+" "+Blocks.doesEmitLight+" "+Blocks.lightValue+" "+Blocks.doesGenNaturally+" "+Blocks.genBelowLevel+" "+Blocks.genRariety+" "+Blocks.genClump+" "+Blocks.blockTexturePath);
projectFile.close();
}
}
When the user first enters the program, the overWriteFile method is called, making the file. Then the user proceeds to another window, where the define the block.* variables and then when a actionPerformed on a button is called, I want addBlock() to be called, formatting the file with the current variables, but when I try to do this multiple times, I gives me console errors... help please.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您想在每次调用
addBlock()
时追加到文件,则删除其中的行projectFile.close()
(或者可能更好,将其更改为 <代码>projectFile.flush()。If you want to append to the file each time
addBlock()
is called, then remove the lineprojectFile.close()
there (or probably even better, change it toprojectFile.flush()
.在完成之前不要关闭格式化程序。
Don't close the formatter until you're done with it.