【发布时间】:2017-06-29 14:20:40
【问题描述】:
我有一个简单的程序,可以读取命令并执行它们。现在我有这段代码用于将某些文本插入到文本文件中:
示例命令:
INSERT "John Smith" INTO college.student
我的主要方法:
else if(command.substring(0,6).equalsIgnoreCase("INSERT")){
String string = command.substring(7, command.indexOf("INTO") - 1);
String DBNameTBName = command.substring(command.indexOf("INTO") + 5);
String tableName = DBNameTBName.substring(DBNameTBName.indexOf(".") + 1);
String DBName = DBNameTBName.substring(0, DBNameTBName.indexOf("."));
if(DBCommands.insert(string, DBName, tableName)){
statfileWriter.println("Inserted " + string + " into table " + tableName + " in " + DBName);
statfileWriter.println("(" + command + ")");
statfileWriter.flush();
}
else{
errfileWriter.println("Error: Could not insert " + string + " into table " + tableName + " in " + DBName);
errfileWriter.println("(" + command + ")");
errfileWriter.flush();
}
以及它调用的插入方法:
public static boolean insert(String string, String DBName, String tableName){
try{
string = string.substring(string.indexOf('"') + 1, string.lastIndexOf('"')); //removes quotes
File tableToWriteTo = new File(DBName + "/" + tableName + ".txt");
if (!tableToWriteTo.exists()){
return false;
}
PrintWriter writer = new PrintWriter(new FileWriter
(tableToWriteTo, true));
writer.println(string);
writer.close();
return true;
}
catch(Exception e){
return false;
}
}
我的插入方法出现了非常奇怪的行为。它返回 true,因为它总是打印到我的状态日志而不是错误日志。我知道创建 .txt 文件的方法运行良好,我已经对其进行了多次测试,并且 student.txt 文件始终存在。使用我的插入命令,如果我将 File = new File 行更改为:
File tableToWriteTo = new File(tableName + ".txt");
然后不出所料,它使用我的示例命令创建了一个名为“student”的 .txt 文件,但不在“DBName”文件夹中。如果我把它改成这样:
File tableToWriteTo = new File(DBName + "/" + tableName);
然后它会创建一个没有类型的名为“student”的文件(例如,Windows 会询问我想用什么打开它),但会放入我想插入的字符串。我应该注意,如果有多个 INSERT 命令,那么它会按照我的意愿写入所有字符串。
我尝试在我的 main 方法中声明 PrintWriter 和 File 并将它们传递进去,但这也不起作用。
我怎样才能让它写入目录学院的students.txt?
编辑:天哪,我是地球上最愚蠢的人。我没有查看我收到的此任务的完整命令列表,我忘记了有一个删除命令,它们都在工作。我会删除这个问题,但我会留下这个问题,以防将来有人想查看 FileWriter 的示例。
【问题讨论】:
标签: java string io filewriter printwriter