【发布时间】:2017-02-21 01:56:17
【问题描述】:
我创建了一个程序,其中有一个名为 groups.txt 的文件。此文件包含名称列表。要删除一个组,它必须存在于文件中。我使用 Scanner 方法在每一行中搜索名称。如果它包含该行,则将 val 设置为 1。这会触发 val == 1 条件。在此期间我想做的是尝试从 groups.txt 文件中删除 groupName 。为此,我创建了一个名为 TempFile 的新 txt 文件,该文件复制了 groups.txt 中除 groupName 之外的所有名称。然后将该文件重命名为 groups.txt 并删除旧的 groups.txt 文件。
一切都按预期工作,除了重命名。 temp.txt 文件仍然存在,groups.txt 文件没有改变。我检查了布尔成功,它总是返回为假。任何想法如何解决这个问题?
if (method.equals("delete group")){
int val = 0;
String groupName = myClient.readLine();
try {
Scanner file = new Scanner(new File("groups.txt"));
while (file.hasNextLine()){
String line = file.nextLine();
if (line.indexOf(groupName) != -1){
val = 1;
}
}
if (val == 1){
try {
File groupFile = new File("groups.txt");
File tempFile = new File("temp.txt");
BufferedReader reader = new BufferedReader(new FileReader(groupFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String currentLine;
System.out.println(groupName);
while ((currentLine = reader.readLine()) != null){
String trimLine = currentLine.trim();
if (trimLine.equals(groupName)){
continue;
} else {
writer.write(currentLine + System.getProperty("line.separator"));
}
}
writer.close();
reader.close();
groupFile.delete();
boolean success = tempFile.renameTo("groups.txt");
} catch (IOException f){
System.err.println("File Not Found: " + f.getMessage());
} }
} catch (FileNotFoundException f){
System.err.println("File Not Found Exception: " + f.getMessage());
}
}
上面的代码:
if (command.equals("group")){
String method = myClient.readLine();
if (method.equals("create group")){
String groupName = myClient.readLine();
int val = 0;
try {
Scanner file = new Scanner(new File("groups.txt"));
while (file.hasNextLine()){
String line = file.nextLine();
if (line.indexOf(groupName) != -1){
Report.error("group name already exists, please pick another");
val = 1;
}
}
} catch (FileNotFoundException f){
System.err.println("File Not Found: " + f.getMessage());
}
if (val == 0){
try {
PrintWriter out = new PrintWriter(new FileWriter("groups.txt", true));
out.println(groupName);
out.close();
} catch (IOException e){
Report.error("IOException: " + e.getMessage());
}
}
在代码的第二部分,这是我最初更新 groups.txt 文件的地方。因此,每次用户添加组时,它都会通过在文件末尾添加新的 groupName 来更新 groups.txt 文件。首先,我使用 Scanner 确保 groupName 不存在。 myClient 是一个 BufferedReader,它从另一个类中读取,该类存储用户在命令行中键入的内容。
【问题讨论】:
-
查看
groupFile.delete()的返回值 -
该值返回false :(
-
实际上,@HappyHal 可能会提到关闭正在打开的扫描仪
groups.txt -
在我关闭 BufferedReader 和 BufferedWriter 后立即关闭扫描仪时出现同样的问题。除非我把它放在错误的地方?
-
@assassinweed2 好吧,我仍然建议您在 delete() 行设置断点来检查所有内容...这可能是您的计算机问题,但您错过某些东西的可能性更高...如果创建命令后您忘记关闭流然后执行删除命令?因为我只测试了删除命令。
标签: java file java.util.scanner bufferedreader bufferedwriter