具有 rewind()/reset() 功能的 java 文件输入 [英] java file input with rewind()/reset() capability

查看:21
本文介绍了具有 rewind()/reset() 功能的 java 文件输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要编写一个函数来接收某种输入流(例如 InputStream 或 FileChannel),以便分两次读取大文件:一次是预先计算一些容量,第二次是执行真正的"工作.我不希望将整个文件一次加载到内存中(除非它很小).

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).

是否有合适的 Java 类提供此功能? FileInputStream 本身不支持 mark()/reset().我认为 BufferedInputStream 可以,但我不清楚它是否必须存储整个文件才能执行此操作.

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 非常简单,您只需使用 fseek()、ftell() 和 rewind().:-(

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

推荐答案

我认为引用 FileChannel 的答案很重要.

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

这是封装此功能的输入流的示例实现.它使用委托,所以它不是一个真正的 FileInputStream,而是一个 InputStream,这通常就足够了.如果需要,可以类似地扩展 FileInputStream.

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);
    }
}

这篇关于具有 rewind()/reset() 功能的 java 文件输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆