【发布时间】:2013-09-04 15:23:54
【问题描述】:
我正在使用 Apache Commons Compress 创建 tar 存档并解压缩它们。我的问题始于这种方法:
private void decompressFile(File file) throws IOException {
logger.info("Decompressing " + file.getName());
BufferedOutputStream outputStream = null;
TarArchiveInputStream tarInputStream = null;
try {
tarInputStream = new TarArchiveInputStream(
new FileInputStream(file));
TarArchiveEntry entry;
while ((entry = tarInputStream.getNextTarEntry()) != null) {
if (!entry.isDirectory()) {
File compressedFile = entry.getFile();
File tempFile = File.createTempFile(
compressedFile.getName(), "");
byte[] buffer = new byte[BUFFER_MAX_SIZE];
outputStream = new BufferedOutputStream(
new FileOutputStream(tempFile), BUFFER_MAX_SIZE);
int count = 0;
while ((count = tarInputStream.read(buffer, 0, BUFFER_MAX_SIZE)) != -1) {
outputStream.write(buffer, 0, count);
}
}
deleteFile(file);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (outputStream != null) {
outputStream.flush();
outputStream.close();
}
}
}
每次我运行代码时,compressedFile 变量为空,但 while 循环正在遍历我的测试 tar 中的所有条目。
你能帮我理解我做错了什么吗?
【问题讨论】:
-
尝试像这样创建输出流: outputStream= new FileOutputStream(new File(entry.getName()));
-
我需要创建一个临时文件。我可以使用 File.createTempFile 代替 new File 吗?
-
我在下面回复了一个完整的答案...
标签: java apache-commons apache-commons-compress