我使用 FileChannel
和 FileInputStream
进行了从 File
fromFile 到 File
toFile 的简单文件复制。
代码基本上是这样的:
source = new FileInputStream(fromFile).getChannel();
destination = new FileOutputStream(toFile, false).getChannel(); // overwrite
destination.transferFrom(source, 0, source.size());
其中 fromFile
和 toFile
是正确的 File
对象。
现在,我不想直接从 fromFile
复制,而是想使用 GZIP(在 Java 库中找到)压缩其内容,然后复制到 toFile
。同样相反,当我从 toFile
传输回来时,我也想解压缩它。
我想知道有没有像这样的简单方法
source = new GZIPCompressInputStream(new FileInputStream(fromFile)).getChannel();
或
source = new GZIPDecompressInputStream(new FileInputStream(fromFile)).getChannel();
并且所有其余代码保持不变。您对最干净的解决方案有什么建议吗?
谢谢..
最佳答案
您可以将 FileInputStream
包装在 GZIPInputStream
中,如下所示:
InputStream 输入 = new GZIPInputStream(yourCompressedInput);
为了在写入时进行压缩,您应该使用GZIPOutputStream。
祝你好运。
关于java - NIO GZIP 压缩和文件复制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29365879/