public void removeLine(String s) throws IOException, FileNotFoundException{
File tempFile = new File("temp.txt");
FileInputStream reader = new FileInputStream(sharkFile);
Scanner scanner = new Scanner(reader);
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile, true));
String currentLine;
while(scanner.hasNextLine()){
currentLine = scanner.nextLine();
String trimmedLine = currentLine.trim();
System.out.println(trimmedLine);
trimmedLine.equals(sharkName);
if(trimmedLine.equals(sharkName)) continue;
writer.write(currentLine + System.getProperty("line.separator"));
}
scanner.close();
scanner = null;
reader.close();
writer.flush();
writer.close();
writer = null;
System.gc();
if(!sharkFile.delete()){
System.out.println("Could not delete file d");
return;
}
if(!tempFile.renameTo(sharkFile)){
System.out.println("Could not rename file");
return;
}
}
我已经浏览了 stackoverflow 上的许多线程并实现了这些更改,但我的文件就是无法删除。感谢您的帮助。
最佳答案
File
API 在解释失败原因方面是出了名的薄弱,例如File.delete()
只是返回一个 boolean
,而值 false
无法解释原因。
改用新的 Path
API。
另外,请(请!)使用 try-with-resources。
Scanner
速度很慢,因此最好使用 BufferedReader
,并且要使用换行符写回行,请使用 PrintWriter
。
Path sharkPath = sharkFile.toPath();
Path tempPath = Paths.get("temp.txt");
Charset cs = Charset.defaultCharset();
try (BufferedReader reader = Files.newBufferedReader(sharkPath, cs);
PrintWriter writer = new PrintWriter(Files.newBufferedWriter(tempPath, cs, StandardOpenOption.CREATE, StandardOpenOption.APPEND, StandardOpenOption.WRITE)))) {
for (String currentLine; (currentLine = reader.readLine()) != null; ) {
String trimmedLine = currentLine.trim();
System.out.println(trimmedLine);
if (! trimmedLine.equals(sharkName))
writer.println(currentLine);
}
}
Files.delete(sharkPath); // throws descriptive exception if cannot delete
Files.move(tempPath, sharkPath); // throws exception if cannot move
关于java - 为什么无论我为什么删除我的文件都不会删除?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36104312/