阿里面试题: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);
    }

所以问题就转变成调用这个方法就行了,这个就不难了。。反射可以轻松搞定。下面是我做了一个测试

  @Test
    public 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 读了两遍这个文件。 

猜你喜欢

转载自blog.csdn.net/v5_BAT/article/details/85014223
今日推荐