Java编程中文件的删除和重命名

Java编程中文件的删除和重命名,java,Java,我需要帮助在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.*

我需要帮助在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();
    }
}

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

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

为了简化问题并更好地进行调试,只需创建文件而不是写入文件——使用file.createNewFile()


可能您的问题与。

要创建临时文件,您应该使用
File.createTempFile(字符串前缀、字符串后缀、文件目录)。不需要调用
pw.flush();`每写一行之后。通常在
close()
之前调用它就足够了。您应该确保关闭流,将关闭放在finally块中,否则您可能无法删除或删除文件。例如,
try{…}ffinally{close(pw);close(br);}
其中close是一个静态方法,如
static void close(Reader r){if(r!=null)try{r.close();}catch(异常e){//log}}
在close之前不需要调用flush()。