2015-12-04 107 views
0

cur文件似乎没有被删除,临时文件也没有被重命名。文件未重命名或删除

private class editClassListener implements ActionListener 
     { 
      public void actionPerformed(ActionEvent e) 
      { 
       File temp = new File("courseTemp.bin"); 
       File cur = new File("course.bin"); 
       ArrayList<Course> courses = new ArrayList<Course>(); 
       int count = 0; 
       try { 
        FileInputStream fin = new FileInputStream(cur); 
        while(true) 
        { 
         try 
         { 
          ObjectInputStream oin = new ObjectInputStream(fin); 
          Course c = (Course) oin.readObject(); 
          courses.add(c); 
         }catch (EOFException eofException){ 
          break; 
         } catch (IOException e1) { 
          e1.printStackTrace(); 
         } catch (ClassNotFoundException e1) { 
          e1.printStackTrace(); 
         } 
        } 
        while(count < courses.size()) 
        { 
         if(enterCourseID.getText().equals(courses.get(count).getCourseID())) 
         { 
          courses.get(count).setDescription(enterCourseDescription.getText()); 
          courses.get(count).setSemester((String) semesterBox.getSelectedItem()); 
          courses.get(count).setYear(yearBox.getSelectedIndex()); 
         } 
        } 
        temp.renameTo(cur); 
        cur.delete(); 
        temp.delete(); 
        fin.close(); 

        FileOutputStream fos = new FileOutputStream(temp); 
        courses.trimToSize(); 
        count = 0; 
        while(count < courses.size()) 
        { 
          ObjectOutputStream oop = new ObjectOutputStream(fos); 
          oop.writeObject(courses.get(count)); 
          count++; 
        } 

       } catch (FileNotFoundException e1) { 
        // TODO Auto-generated catch block 
        e1.printStackTrace(); 
       } catch (IOException e1) { 
        // TODO Auto-generated catch block 
        e1.printStackTrace(); 
       }    
      } 
     } 
+0

我看到你永远不会关闭任何流。可能想这样做。 'oop.close();'和其他任何你使用的流.... – 3kings

回答

0

两个File.delete()File.renameTo()不抛出一个异常,而是返回false如果不能执行底层操作系统运行。对于原因都依赖你的系统上,但尤其包括:

  • 您要重命名/删除该文件是在使用中(即开放式流)
  • 该文件是由OS保护(权限不足)
  • 在重命名的情况下:以新名称的文件已经存在

在你的情况,至少第一点是真实的。在尝试删除cur之前,只需简单地关闭FileInputStream fin即可。至于重命名,您可能需要在重命名temp之前先删除cur

顺便说一句,该工具类java.nio.file.Files提供的方法(move() & delete()),用于重命名和删除,其抛出IOException,如果操作失败,失败的错误消息的原因。

+0

感谢您的信息。关闭FileInputStream,FileOutputStream并在重命名之前删除旧文件解决了我的问题。 – riskitall69

相关问题