Java 文件无法删除或重命名

标签 java file file-rename delete-file

请参阅下面的代码: 我可以在文件的一行中写入一个 key 和一个字符串。如果 key 已经存在,我想通过创建一个新文件来覆盖它,并用源文件的内容填充它。最后,我将删除旧文件并重命名我的临时文件。但这不起作用。正如您所看到的,我打印了删除和 renameTo 方法的 boolean 值。两者都返回“false”。

我在其他一些线程中读到,我必须关闭与我的文件联系的所有读取器和写入器,以便能够重命名或删除它。

你看到我的错了吗?

(请注意,有些评论是用德语写的)

public static boolean dini_Set(String filepath, String key, String value) throws IOException
{
    if(key.length() <= 0 || value.length() <= 0) return false;

    String pfilepath = rootdirectory.concat(filepath);
    File pfile = new File(pfilepath);
    //dini_Remove(filepath.concat(".part"));

    if(dini_Exists(filepath) == false) return false;

    // Checkt ob der Key schon existiert

    FileReader fr = new FileReader(pfilepath);
    BufferedReader br = new BufferedReader(fr);

    String ausw;
    boolean foundkeybool = false;
    while((ausw = br.readLine()) != null)
    {
       String foundkey = ausw.substring(0,ausw.indexOf("="));
       //System.out.println(foundkey);
       if(foundkey.equals(key))
       {
           foundkeybool = true;
           System.out.println(foundkeybool);

           // Key exists and content has to be overwritten

           String newline = key.concat("=").concat(value);

           String tmpdir = rootdirectory.concat("tmp.tmp");
           File tmp = new File(tmpdir);
           tmp.createNewFile();
           String currentLine;
           FileWriter fw = new FileWriter(tmpdir);
           BufferedWriter bw = new BufferedWriter(fw);

           br.close();
           fr.close();

           fr = new FileReader(pfilepath);
           br = new BufferedReader(fr);

           while((currentLine = br.readLine()) != null) 
           {
                // trim newline when comparing with lineToRemove
                String trimmedLine = currentLine.trim();
                System.out.println(trimmedLine);
                if(trimmedLine.equals(ausw)) 
                {
                    System.out.println("Austauschen: "+newline);
                    bw.write(newline);
                }
                else
                {
                    bw.write(currentLine);
                    System.out.println("Lassen: "+currentLine);
                }
                bw.newLine();
           }

           br.close();
           fr.close();
           bw.close();
           fw.close();
           tmp.setWritable(true);
           pfile.setWritable(true);
           // boolean removed = dini_Remove(filepath);
           boolean removed = pfile.delete();
           System.out.println("Datei wurde gelöscht: "+removed);
           boolean renamed = tmp.renameTo(pfile);
           System.out.println("Datei umbenannt: "+renamed);
           break;
       }
    }

    // if key does now exists we can create a new one
    if(foundkeybool == false)
    {
        FileWriter fw = new FileWriter(pfilepath,true);
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write(key.concat("=").concat(value));
        bw.newLine();
        bw.close();
    }   
    return true;
}

最佳答案

这可能无法解决您的问题,但会让您更接近。

您必须确保您打开的任何资源都已正确关闭。目前在您的代码中,如果由于某种原因引发异常,您的任何资源都不会被关闭。

即使您对处理方法内的异常不感兴趣,您仍然应该将文件访问代码包装在 try-finally block 中

FileReader fr = null;
BufferedReader br = null;
try {
    fr = new FileReader(pfilepath);
    br = new BufferedReader(fr);    
    //...//
} finally {
    try {
        br.close();
    } catch (Exception exp) {
    }
    try {
        fr.close();
    } catch (Exception exp) {
    }
}

您可能会发现您只需要关闭 BufferedReader 并且它应该在其子 Reader 上调用 close,但我偏执于确保一切都是干净的

如果您使用的是 Java 7,您不妨查看 The try-with-resources Statement

已更新

我不确定你的代码是否有意义。基本上,您应该做的是读取整个源文件并将其写入临时位置(因为您事先不知道 key 是否需要更新,而且您可能需要读取源文件才能找到出)。

完成此操作后,如果您对临时文件进行了更改,请删除源文件并将临时文件重命名到原来的位置。

你的代码对我来说效率很低......

关于Java 文件无法删除或重命名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17808892/

相关文章:

PHP try catch block 不捕获

linux - Bash oneliner 重命名文件名

java - 使 GWT 应用程序即使在低带宽下也能工作

java - 如何从 Java jar 文件中读取资源文件?

java - 以编程方式以受控方式增加 CPU 使用率

java - 是否可以从嵌套类引用外部类指针?

file - 如何在 Nautilus/Caja linux 文件管理器中获取视频文件的分辨率(宽度和高度)?

file - 如何区分同一ip地址(wifi)中的两个或多个设备?

c++ - directory_iterator file_iter 重命名文件夹中的文件

python - 使用 Python 中的 glob 重命名多个文件(文件已存在)