如何将 ArchiveEntry 转换为 InputStream?
How to convert ArchiveEntry to InputStream?
我正在使用
阅读tar.gz
档案
ArchiveEntry entry = tarArchiveInputStream.getNextEntry();
问题:如何将此 ArchiveEntry 转换为 InputStream
,以便我可以实际读取文件并将其处理为 String
?
已经是InputStream
.
byte[] buf = new byte[(int) entry.getSize()];
int k = tarArchiveInputStream.read(buf, 0, buf.length);
String s = new String(buf, 0, k);
您可以使用 IOUtils 完整读取 InputStream:
import org.apache.commons.compress.utils.IOUtils
byte[] buf = new byte[(int) entry.getSize()];
int readed = IOUtils.readFully(tarArchiveInputStream,buf);
//readed should equal buffer size
if(readed != buf.length) {
throw new RuntimeException("Read bytes count and entry size differ");
}
String string = new String(buf, StandardCharsets.UTF_8);
如果您的文件不是 utf-8 编码,请在字符串的构造函数中使用它而不是 utf-8。
如果真的要一个一个读取文件,其实TarEntry里面就保存了File对象:
This class represents an entry in a Tar archive. It consists of the entry's header, as well as the entry's File.
因此只需初始化另一个 FileInputStream 就足够了:
import org.apache.commons.io.IOUtils;
String file = IOUtils.toString(new FileInputStream(entry.getFile());
我正在使用
阅读tar.gz
档案
ArchiveEntry entry = tarArchiveInputStream.getNextEntry();
问题:如何将此 ArchiveEntry 转换为 InputStream
,以便我可以实际读取文件并将其处理为 String
?
已经是InputStream
.
byte[] buf = new byte[(int) entry.getSize()];
int k = tarArchiveInputStream.read(buf, 0, buf.length);
String s = new String(buf, 0, k);
您可以使用 IOUtils 完整读取 InputStream:
import org.apache.commons.compress.utils.IOUtils
byte[] buf = new byte[(int) entry.getSize()];
int readed = IOUtils.readFully(tarArchiveInputStream,buf);
//readed should equal buffer size
if(readed != buf.length) {
throw new RuntimeException("Read bytes count and entry size differ");
}
String string = new String(buf, StandardCharsets.UTF_8);
如果您的文件不是 utf-8 编码,请在字符串的构造函数中使用它而不是 utf-8。
如果真的要一个一个读取文件,其实TarEntry里面就保存了File对象:
This class represents an entry in a Tar archive. It consists of the entry's header, as well as the entry's File.
因此只需初始化另一个 FileInputStream 就足够了:
import org.apache.commons.io.IOUtils;
String file = IOUtils.toString(new FileInputStream(entry.getFile());