实现思路,新建一个ReverseInputStream类继承FilterInputStream并覆盖父类的read()方法。
第一次调用read()方法时,用父类的readAllBytes()方法把文件的全部内容读取到一个byteBuffer的缓存上,并设置读取索引currentIndex的值为byteBuffer.length-1。
然后返回byteBuffer[currentInde--],如果文件内容较大的话第一次调用read方法等待的时间可能会比较久。
实现代码
public class ReverseInputStream extends FilterInputStream {
private byte[] byteBuffer;
private int currentInde;
protected ReverseInputStream(InputStream in) {
super(in);
}
@Override
public int read() throws IOException {
if(byteBuffer == null){
byteBuffer = in.readAllBytes();
currentInde=byteBuffer.length-1;
}
if(currentInde < 0) return -1;
return byteBuffer[currentInde--];
}
}
测试代码
public class Test {
public static void main(String[] args) throws IOException {
InputStream inputStream = new ReverseInputStream(new BufferedInputStream(new FileInputStream(("D:\\Downloads\\DesignPattern\\src\\week2\\lab2\\test.txt"))));
int c=0;
while((c=inputStream.read() ) >= 0){
System.out.print((char)c);
}
inputStream.close();
}
}
文件内容
Reverse Print File Content.
运行结果