java rewind(),带有rewind()/ reset()功能的java文件输入

I need to write a function that takes in some kind of input stream thing (e.g. an InputStream or a FileChannel) in order to read a large file in two passes: once to precompute some capacities, and second to do the "real" work. I do not want the whole file loaded into memory at once (unless it is small).

Is there an appropriate Java class that provides this capability? FileInputStream itself does not support mark()/reset(). BufferedInputStream does, I think, but I'm not clear whether it has to store the whole file to do this.

C is so simple, you just use fseek(), ftell(), and rewind(). :-(

解决方案

I think the answers referencing a FileChannel are on the mark .

Here's a sample implementation of an input stream that encapsulates this functionality. It uses delegation, so it's not a true FileInputStream, but it is an InputStream, which is usually sufficient. One could similarly extend FileInputStream if that's a requirement.

Not tested, use at your own risk :)

public class MarkableFileInputStream extends FilterInputStream {

private FileChannel myFileChannel;

private long mark = -1;

public MarkableFileInputStream(FileInputStream fis) {

super(fis);

myFileChannel = fis.getChannel();

}

@Override

public boolean markSupported() {

return true;

}

@Override

public synchronized void mark(int readlimit) {

try {

mark = myFileChannel.position();

} catch (IOException ex) {

mark = -1;

}

}

@Override

public synchronized void reset() throws IOException {

if (mark == -1) {

throw new IOException("not marked");

}

myFileChannel.position(mark);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值