有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

无法删除或重命名Java文件

请参见下面的我的代码: 我可以在文件的一行中写入一个键和一个字符串。如果密钥已经存在,我想通过创建一个新文件并用源文件的内容填充来覆盖它。最后,我将删除旧文件并重命名我的临时文件。但它不起作用。如您所见,我打印布尔值以删除和重命名方法。两者都返回为“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;
}

共 (2) 个答案

  1. # 1 楼答案

    这也许不能解决你的问题,但会让你更接近

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

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

    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,但我偏执于确保一切都是干净的

    如果您使用的是Java7,您可能希望看看The try-with-resources Statement

    已更新

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

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

    你的代码在我看来非常低效

  2. # 2 楼答案

    Okai,我想给你一个简短的代码更新

    我改变了这种方式,现在它是工作,因为它应该

    你有更多的东西我可以改变优化代码吗

    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
    
        boolean foundkeybool = false;
        File tmp = null;
    
        try(BufferedReader br = new BufferedReader(new FileReader(pfilepath)))
        {           
            String ausw;
    
            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");
                   tmp = new File(tmpdir);
                   tmp.createNewFile();
                   String currentLine;
    
                   try(BufferedWriter bw = new BufferedWriter(new FileWriter(tmpdir)))
                   {
                       try(BufferedReader br2 = new BufferedReader(new FileReader(pfilepath)))                
                       {
                           while((currentLine = br2.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();
                           }
                       }
                   }    
    
    
    
                   break;
               }
            }
        }
    
        if(foundkeybool == true)
        {
            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);
        }
        else //(foundkeybool == false) if key does now exists we can create a new one
        {
            try(BufferedWriter bw = new BufferedWriter(new FileWriter(pfilepath,true)))
            {
                bw.write(key.concat("=").concat(value));
                bw.newLine();
                bw.close();
            }     
        }   
        return true;
    }