首页 > 解决方案 > ByteArrayInputStream 到 FileInputStream 而不将文件写入硬盘

问题描述

byte[]我从数组中的数据库中读取了一个文件,使用ByteArrayInputStream.

InputStream input = new ByteArrayInputStream(lc.getTable());

为了进一步处理文件,我需要一个FileInputStream. 但我不想先将文件保存在硬盘上再读取。

可以这样做还是必须先写出文件?

标签: javafilefileinputstreambytearrayinputstream

解决方案


并不真地。然后进一步的处理被过度指定;它应该只需要一个 InputStream。Files可以使用该类创建一个临时删除的退出文件。可以创建一个包含额外线程但仍然是物理文件的输入输出管道。可以使用RAM 磁盘上的文件。

但是,我们可以创建自己的 FileInputStream,重定向/委托到您的 ByteArrayInputStream:

public class FakeFileInputStream extends FileInputStream {
    private final InputStream sourceInput;

    //public FakeFileInputStream(String name, InputStream sourceInput)
    //        throws FileNotFoundException {
    //    super(name);
    //    this.sourceInput = sourceInput;
    //}

    // @Torben offered this solution, which does not need an existing file.
    public FakeFileInputStream(InputStream sourceInput) {
        super(new FileDescriptor());
        this.sourceInput = sourceInput;
    }


    @Override
    public int read() throws IOException {
        return sourceInput.read();
    }

    @Override
    public int read(byte[] b) throws IOException {
        return sourceInput.read(b);
    }

    @Override
    public int read(byte[] b, int off, int len) throws IOException {
        return sourceInput.read(b, off, len);
    }

    @Override
    public long skip(long n) throws IOException {
        return sourceInput.skip(n);
    }

    @Override
    public int available() throws IOException {
        return sourceInput.available();
    }

    @Override
    public void close() throws IOException {
        sourceInput.close();
        //super.close();
    }

    @Override
    public FileChannel getChannel() {
        throw new UnsupportedOperationException();
    }

    @Override
    public synchronized void mark(int readlimit) {
        sourceInput.mark(readlimit);
    }

    @Override
    public synchronized void reset() throws IOException {
        sourceInput.reset();
    }

    @Override
    public boolean markSupported() {
        return sourceInput.markSupported();
    }
}

旧注释:注释掉的构造函数会打开传递的文件name,最后关闭它,但什么也不做。您可以传递任何现有文件。

注意:感谢@Torben 提供了一个使用空文件描述符的版本。

(要创建这样一个包装器/委托类:如果 IDE 不提供委托类的生成,只需覆盖所有方法,并将“super.”替换为“delegate”。)


推荐阅读