【问题标题】:Java File cannot be deleted nor renamedJava 文件不能删除也不能重命名
【发布时间】:2015-07-14 22:11:21
【问题描述】:

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

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

你看出我的错了吗?

(注意有些cmets是用德语写的)

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;
}

【问题讨论】:

    标签: java file file-rename delete-file


    【解决方案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,但我对确保一切都是干净的感到偏执

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

    更新

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

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

    你的代码对我来说似乎非常低效......

    【讨论】:

      【解决方案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;
      }
      

      【讨论】:

        猜你喜欢
        • 2016-08-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-08-16
        • 2015-03-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多