【问题标题】:How do I compress a file in GZip format? [duplicate]如何压缩 GZip 格式的文件? [复制]
【发布时间】:2016-11-19 10:24:33
【问题描述】:

在下面的代码中,我可以将文件转换为 gzip,但在这里我提供了静态输入和输出的位置。但我需要动态提供文件名

这里是我使用的例子

String source_filepath = "C:\\Users\\abc\\Desktop\\home6.jpg";
String destinaton_zip_filepath =C:\\Users\\abc\\Desktop\\home6.gzip";

这里代替 home6.jpg 我可以动态地提供任何东西

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;


public class CompressFileGzip {

    public static void main(String[] args) {

        String source_filepath = "C:\\Users\\abc\\Desktop\\home6.jpg";

        String destinaton_zip_filepath = "C:\\Users\\abc\\Desktop\\home6.gzip";



        CompressFileGzip gZipFile = new CompressFileGzip();

        gZipFile.gzipFile(source_filepath, destinaton_zip_filepath);

    }

    public void gzipFile(String source_filepath, String destinaton_zip_filepath) {

        byte[] buffer = new byte[1024];
        try {    
            FileOutputStream fileOutputStream =new FileOutputStream(destinaton_zip_filepath);

            GZIPOutputStream gzipOuputStream = new GZIPOutputStream(fileOutputStream);

            FileInputStream fileInput = new FileInputStream(source_filepath);

            int bytes_read;

            while ((bytes_read = fileInput.read(buffer)) > 0) {

                gzipOuputStream.write(buffer, 0, bytes_read);

            }

            fileInput.close();

            gzipOuputStream.finish();

            gzipOuputStream.close();

            System.out.println("The file was compressed successfully!");

        } catch (IOException ex) {

            ex.printStackTrace();

        }

    }

}

【问题讨论】:

  • 静态值只是您设置并作为参数传递给 gzip 方法的变量。您希望如何提供动态文件名?您可以使用多种可能性,并且有许多 API 提供了这样做的方法。
  • String source_filepath = args[0] 也许?
  • 简单使用7z(7zip有命令行界面)

标签: java command-line command-line-interface command-line-arguments


【解决方案1】:

只需从命令行参数中获取它:

public static void main(String[] args) {
    String source_filepath = args[0];
    String destinaton_zip_filepath = args[1];

请注意,您可能希望在此处添加一些错误检查代码,以确保您确实获得了两个命令行参数、文件存在等。

【讨论】:

  • 线程“main”中的异常 java.lang.ArrayIndexOutOfBoundsException: 0 at CompressFileGzip.main(CompressFileGzip.java:20) 请帮忙
  • @raghu 你需要实际传递命令行参数
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-01
  • 2022-11-21
  • 1970-01-01
  • 1970-01-01
  • 2012-07-01
  • 1970-01-01
相关资源
最近更新 更多