Java 怎么将一个流输出为tgz文件
时间: 2024-03-19 14:46:13 浏览: 20
你可以使用 Java 的 GZIPOutputStream 和 TarArchiveOutputStream 类来将一个流输出为tgz文件。首先,你需要将流包装在 GZIPOutputStream 中,然后将其传递给 TarArchiveOutputStream,最后将其写入到文件中。下面是一个示例代码:
```
import java.io.*;
import org.apache.commons.compress.archivers.tar.*;
import org.apache.commons.compress.compressors.gzip.*;
public class StreamToTgz {
public static void main(String[] args) throws IOException {
InputStream inputStream = // your input stream
OutputStream outputStream = new FileOutputStream("output.tgz");
// wrap the output stream in a Gzip compressor
GzipCompressorOutputStream gzipOutputStream = new GzipCompressorOutputStream(outputStream);
// wrap the Gzip compressor in a Tar archive
TarArchiveOutputStream tarOutputStream = new TarArchiveOutputStream(gzipOutputStream);
// create a Tar entry
TarArchiveEntry entry = new TarArchiveEntry("entryName");
// set the size of the entry
entry.setSize(inputStream.available());
// put the entry in the Tar archive
tarOutputStream.putArchiveEntry(entry);
// copy the input stream to the Tar archive
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
tarOutputStream.write(buffer, 0, bytesRead);
}
// close the Tar entry and output streams
tarOutputStream.closeArchiveEntry();
tarOutputStream.finish();
tarOutputStream.close();
}
}
```
注意:以上代码使用了 Apache Commons Compress 库,你需要将其添加到你的项目中。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)