Java文件句柄释放


1.java代码书写过程,文件资源的释放需要特别谨慎的对待.通常文件资源使用后必须close,然后再删除。

如果先删除但没有close掉,会造成文件句柄未被释放.

eg:

  1. import java.io.File;   
  2. import java.io.FileOutputStream;   
  3. import java.io.IOException;   
  4. public class FileTest {   
  5.     public static void main(String[] args) {   
  6.         File file = new File("/home/admin/a.txt");   
  7. //      File file = new File("c:\\a.txt");   
  8.         FileOutputStream  out = null;   
  9.         try {   
  10.             out = new FileOutputStream(file);   
  11.             file.delete();   
  12.             while(true){   
  13.                 try {   
  14.                     Thread.sleep(1000);   
  15.                 } catch (InterruptedException e) {   
  16.                     e.printStackTrace();   
  17.                 }   
  18.             }   
  19.         } catch (IOException e) {   
  20.             e.printStackTrace();   
  21.         } finally {   
  22.             try {   
  23.                 if(out!=null) {   
  24.                     out.close();   
  25.                 }   
  26.             } catch (IOException e) {   
  27.                 e.printStackTrace();   
  28.             }   
  29.         }   
  30.     }   
  31.        
  32. }  

此时文件关闭了,但是out还持有文件,out未关闭则文件句柄未被释放。造成实际可使用空间小于可使用空间。

2.文件句柄的调试可用lsof 命令进行查看

   lsof -s |grep java

   lsof -s |grep deleted

相关内容