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

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

这会造成实际使用磁盘空间较大,成为瓶颈

eg:

 

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileTest {
	public static void main(String[] args) {
		File file = new File("/home/admin/a.txt");
//		File file = new File("c://a.txt");
		FileOutputStream  out = null;
		try {
			out = new FileOutputStream(file);
			file.delete();
			while(true){
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if(out!=null) {
					out.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
}

 

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

 

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

   lsof -s |grep java

   lsof -s |grep deleted