我正在尝试使用 fileWriter * 将文本数据写入文本文件,但程序创建的文件中没有任何内容... *我可以使用其他文件写入文件的方法,但没有一个对我有用......(对我来说,如何完成它并不重要,只要它有效。)
我在下面添加了我的代码片段,这是CommandInterpretation类中唯一重要的方法。
private static FileWriter writer; //initialized outside so as to last through multiple calls
//Main area, processes the input fed from the user.
public String processInput(String theInput) {
try {
String theOutput = null;
writer = new FileWriter("Default.txt",true); //initialized to a random file, otherwise it doesn't compile as I may have tried to close it without initializing
if (state == ORIGINAL) {
theOutput = "Hello, Master.";
state = PROCESSCMDS;
} else if (state == PROCESSCMDS) {
if (theInput.split(" ")[0].equalsIgnoreCase("save")) {
writer.close();
writer = new FileWriter(theInput.split(" ")[1],true);
theOutput = "Created new file: what's in it? (eof to end)";
state = WRITEFILE;
} else if (theInput.split(" ")[0].equalsIgnoreCase("run")) {
Runtime.getRuntime().exec("cmd /c start " + theInput.split(" ")[1]);
theOutput = "Successfully executed " + theInput.split(" ")[1] + ".";
} else if (theInput.split(" ")[0].equalsIgnoreCase("close")) {
state = ENDPROCESS;
}
} else if (state == WRITEFILE) { //file line input
if (theInput.equalsIgnoreCase("eof")) {
writer.close();
theOutput = "File closed.";
state = PROCESSCMDS;
} else {
writer.write(theInput);
writer.write("\r\n");
theOutput = "Next Line: ";
}
}
if (state == ENDPROCESS) {
theOutput = "Bye.";
state = ORIGINAL;
}
if (theOutput == null)
return "Command not recognized.";
return theOutput;
} catch (Exception e) {return "Something went wrong: " + e.getMessage();}
}
我试着寻找答案,但我能找到的只是一堆类似的问题,人们忘了关闭()他们的文件。
在我的输出中,我看到“文件已关闭。”,所以它必须运行代码的那一部分......即使如此,文件仍为空...
总之,问题是fileWriter正在创建一个名为I assign it的文件,但该文件为空。 Default.txt已创建且为空,这很好,但是创建了输入.split(“”)1并且也是空的。我感谢你们能给我的任何帮助!
提前致谢。
根据请求,使用下面的简单方法调用一些示例:
import java.util.*;
public class test
{
//tester for other program
public static void main(String[] args) {
System.out.println("Starting...");
CommandInterpretation ci = new CommandInterpretation();
Scanner in = new Scanner( System.in );
while (true)
System.out.println(ci.processInput(in.nextLine()));
}
}