我需要编写一个函数,它接受某种输入流的东西(例如一个InputStream或一个FileChannel),以便在两次传递中读取一个大文件:一次预先计算一些容量,二次做"真正的"工作.我不希望一次将整个文件加载到内存中(除非它很小).
是否有适当的Java类提供此功能?FileInputStream本身不支持mark()/ reset().我认为BufferedInputStream确实如此,但我不清楚它是否必须存储整个文件来执行此操作.
C很简单,你只需使用fseek(),ftell()和rewind().:-(
yka*_*ich 25
我认为引用FileChannel的答案是标记的.
这是封装此功能的输入流的示例实现.它使用委托,因此它不是真正的FileInputStream,但它是一个InputStream,通常就足够了.如果这是一个要求,可以类似地扩展FileInputStream.
未经测试,使用风险自负:)
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);
}
}
Run Code Online (Sandbox Code Playgroud)
eri*_*son 22
BufferedInputStreammark通过缓冲内存中的内容来支持.最好保留用于可预测大小的相对较小的预测.
相反,RandomAccessFile可以直接使用,也可以作为具体的基础InputStream,用rewind()方法扩展.
或者,FileInputStream可以为每个通行证打开一个新的.
小智 19
如果从中获取了关联FileChannel,则FileInputStream可以使用position方法将文件指针设置为文件中的任何位置.
FileInputStream fis = new FileInputStream("/etc/hosts");
FileChannel fc = fis.getChannel();
fc.position(100);// set the file pointer to byte position 100;
Run Code Online (Sandbox Code Playgroud)
RandomAccessFile就是你想要的:
| 归档时间: |
|
| 查看次数: |
41672 次 |
| 最近记录: |