java - 为什么无论我为什么删除我的文件都不会删除?

标签 java java.util.scanner bufferedreader delete-file streamwriter

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/

相关文章:

java - 如何更新进度条以显示 Activity 期间的进度(当方法正在运行时)?

java - 扫描仪在使用 next() 或 nextFoo() 后跳过 nextLine()?

java - 为什么我无法将文本文件中的行添加到 Java 中的 ArrayList 中?

go - bufio.Writer写入后,bufio.Reader不会从文件中读取任何内容

在方法之间传递的 Java 套接字

java - 如果读取相同的文本则停止 BufferedReader

java - (否)Java 中的属性?

java - 如何知道 MVC View 中哪个字段要更新?

java - 如何将地理点经度+纬度转换为两倍?

Java 扫描仪在 ""的情况下忽略 csv 中的分隔符