利用反射重複使用FileInputStream導致文件無法刪除

在之前某個項目中,上傳的文件需要進行多次處理,所以需要多次重複使用FileInputStream。爲了節約資源,我使用反射調用FileInputStream中的私有方法open(),多次讀取文件。以上的功能都沒有問題,但在最後關閉了FileInputStream流後,文件無法刪除。

File file = new File("D:\\csdn_js.txt");
InputStream in = new FileInputStream(file);
byte[] b = new byte[4096];
int length = 0;
while ((length = in.read(b)) > -1) {
	System.out.println(length);
}
System.out.println(file.canRead());
System.out.println(file.canWrite());
System.out.println(file.canExecute());
in.close();
Method open = FileInputStream.class.getDeclaredMethod("open", String.class);
open.setAccessible(true);
open.invoke(in, file.getAbsolutePath());
while ((length = in.read(b)) > -1) {
	System.out.println(length);
}
in.close();
open = null;

System.gc();

File file2 = new File("D:\\csdn_js2.txt");

System.out.println(open);// null
System.out.println(file.delete());// false
System.out.println(file.renameTo(file2));// false
System.out.println(file.canWrite());// true
System.out.println(file.canRead());// true
System.out.println(file.canExecute());// true

推測是FileInputStream調用native方法open0()時導致文件被佔用,流打開了多次,但只關閉了一次,所以native方法中某些資源沒有回收,導致文件無法刪除和移動。由於文件可能很大,不適合緩存在內存,所以最後new了多個FileInputStream。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章