0

我需要帮助在 Java 编程中删除然后重命名文件。我的问题是原始文件无法删除,第二个文件无法重命名。这是片段代码。任何建议将不胜感激。

import java.awt.event.*;
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;




public void deleteLine(String content) {
    try {

        File inFile = new File("football.dat");
        if (!inFile.isFile()) {
            System.out.println("Parameter is not an existing file");
            return;
        }
        File tempFile = new File(inFile.getAbsolutePath() + "2");
        BufferedReader br = new BufferedReader(new FileReader(inFile));
        PrintWriter pw = new PrintWriter(new FileWriter(tempFile), true);

        String linetobeempty = null;
        while ((linetobeempty = br.readLine()) != null) {

            if (!linetobeempty.trim().equals(content)) {
                pw.println(linetobeempty);
                pw.flush(); System.out.println(linetobeempty);
            }
        }

        pw.close();        
        br.close();
       boolean b = inFile.delete();

        if (!b) {
            System.out.println("Could not delete file");
            return;
        }

        //Rename the new file to the filename the original file had.
        if (!tempFile.renameTo(inFile)) {
            System.out.println("Could not rename file");
        }


    } catch (FileNotFoundException ex) {
        ex.printStackTrace();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}
4

2 回答 2

1

你在 Windows 上吗?在 Windows 上,如果任何进程在文件上具有文件句柄,则取消链接和重命名将失败(与 UNIX 不同)。我什至注意到,在 Java 中进行文件 I/O 测试时,有时您需要在文件写入和文件删除之间让操作系统休息一下。renameTo 和 delete上的文档给出了一些有限的见解。

为了简化您的问题并更好地调试它,只需创建文件而不是写入文件——使用 File.createNewFile()。

可能您遇到与无法删除文件 Java相同的问题。

于 2012-04-14T20:35:06.373 回答
1

此代码段中没有任何内容是文件未被删除的直接原因。问题更深层次——权限,由其他进程打开,通常的东西。检查所有这些。当然,删除失败后重命名失败的原因是显而易见的,所以目前你知道的只有一个问题。

于 2012-04-14T19:51:32.523 回答