java - ByteArrayInputStream 到 FileInputStream 而不将文件写入硬盘
问题描述
byte[]
我从数组中的数据库中读取了一个文件,使用ByteArrayInputStream
.
InputStream input = new ByteArrayInputStream(lc.getTable());
为了进一步处理文件,我需要一个FileInputStream
. 但我不想先将文件保存在硬盘上再读取。
可以这样做还是必须先写出文件?
解决方案
并不真地。然后进一步的处理被过度指定;它应该只需要一个 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”。)
推荐阅读
- python - Matplotlib y 轴范围
- android - 从 kotlin dsl gradle 文件中的 rootproject 文件应用插件
- javascript - Stripe:印度发行的卡的非印度货币支付失败
- r - R - 如何不将所有条件与pairwise.t.test进行比较
- angular - OpenLayers 点击图标不会触发交互
- c# - 根据app设置中的条件更改资源文件中的值(asp.net core)
- azure - 将应用上传到 Azure 广告,无需注册新应用
- c# - 当我尝试重命名文件时,遇到有关 File.Move 方法的错误
- c# - 产生相同蛇食的倍数的问题
- arrays - C 在屏幕上打印随机数