【发布时间】:2016-08-24 16:02:42
【问题描述】:
在为我的类创建方法时,我遇到了一个意想不到的问题。我尝试过其他人的解决方案,但它们对我不起作用。我的方法应该简单地找到指定的行,复制文件跳过不必要的行,删除原始文件并将临时文件重命名为原始文件的名称。它按预期成功创建了新文件,但由于无法将临时文件重命名为原始文件,因此无法删除前一个文件。我想不通,为什么?
void lineDelete(String file_name, String line_to_erase){
try {
int line_number = 0;
String newline = System.getProperty("line.separator");
File temp = new File("temporary.txt");
File theFile = new File(file_name+".txt");
String path = theFile.getCanonicalPath();
File filePath = new File(path);
BufferedReader reader = new BufferedReader(new FileReader(file_name + ".txt"));
BufferedWriter writer = new BufferedWriter(new FileWriter(temp));
String lineToRemove = line_to_erase;
String currentLine;
while((currentLine = reader.readLine()) != null) {
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(lineToRemove)){
continue;
}
writer.write(currentLine + newline));
}
writer.close();
reader.close();
filePath.delete();
temp.renameTo(theFile);
}
catch (FileNotFoundException e){
System.out.println(e);
}
catch (IOException e){
System.out.println(e);
}
【问题讨论】:
-
你有什么异常吗?
-
发布的代码甚至无法编译。 tempFile 未定义。贴出实际代码,确实有问题。使用 Files.delete 和 Files.move:你会得到解释问题所在的 execptions。
-
不,我没有得到任何异常,并且对 tempFile 感到抱歉,忘记将其更改为 temp。我编辑了原始代码,使变量更清晰。
-
您的项目在哪里?工作区的位置?
-
C:/users/user/sublime text/java/,但这是一个项目,它需要在任何目录中运行。所以移动到任意目录并编译后,应该可以顺利运行