阿里面试题:FileInputStream 在使用完以后,不关闭流,想二次使用可以怎么操作
生活随笔
收集整理的這篇文章主要介紹了
阿里面试题:FileInputStream 在使用完以后,不关闭流,想二次使用可以怎么操作
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
FileInputStream 中有一個方法是open 方法調用的是本地的打開文件的方法,fileinputStream 就是通過這個方法來打開文件的,所以如果要重寫讀取這個文件,不重新創建對象,那么只要調用這個方法就可以了。
/*** Opens the specified file for reading.* @param name the name of the file*/private native void open0(String name) throws FileNotFoundException; /*** Opens the specified file for reading.* @param name the name of the file*/private void open(String name) throws FileNotFoundException {open0(name);}所以問題就轉變成調用這個方法就行了,這個就不難了。。反射可以輕松搞定。下面是我做了一個測試
@Testpublic void testFileinp() throws IOException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {FileInputStream inputStream=new FileInputStream("E:/test/te.txt");FileOutputStream outputStream=new FileOutputStream("E:/test/te2.txt");FileOutputStream outputStreams=new FileOutputStream("E:/test/te3.txt");int len;byte [] by=new byte[8192];while ((len=inputStream.read(by))!=-1){outputStream.write(by,0,len);}if(inputStream.read()==-1){Class in=inputStream.getClass();Method openo= in.getDeclaredMethod("open0", String.class);openo.setAccessible(true);openo.invoke(inputStream,"E:/test/te.txt");}while ((len=inputStream.read(by))!=-1){outputStreams.write(by,0,len);}outputStream.close();}?
結果當然是在 沒有,關閉流的情況下使用 inputStream 讀了兩遍這個文件。?
總結
以上是生活随笔為你收集整理的阿里面试题:FileInputStream 在使用完以后,不关闭流,想二次使用可以怎么操作的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: webstorm安装注意
- 下一篇: PyTorch 进阶学习(二)————S