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