Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/341.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用java压缩时,gzip文件中未保留文件格式/扩展名_Java_Compression_Gzip - Fatal编程技术网

使用java压缩时,gzip文件中未保留文件格式/扩展名

使用java压缩时,gzip文件中未保留文件格式/扩展名,java,compression,gzip,Java,Compression,Gzip,我试着把一个文件压缩成gzip格式。 源文件的文件格式/扩展名不保留在压缩的.gz文件中 我使用以下java代码来gzip文件 如果toFile=test.csv.gz 但是如果toFile=test.gz 我担心的是,我不想以gzip文件的名义使用源文件格式 代码: GZIPOutputStream只是压缩数据,它不像ZipFilewouldGZip那样存储“文件条目”信息,它只是一种压缩方案,而不是多文件归档格式。没有内部存储的文件名,这就是为什么通常名为x.y的文件被压缩为x.y.gz的原

我试着把一个文件压缩成gzip格式。 源文件的文件格式/扩展名不保留在压缩的.gz文件中

我使用以下java代码来gzip文件

如果
toFile=test.csv.gz

但是如果
toFile=test.gz

我担心的是,我不想以
gzip
文件的名义使用源文件格式

代码:


GZIPOutputStream
只是压缩数据,它不像
ZipFile
wouldGZip那样存储“文件条目”信息,它只是一种压缩方案,而不是多文件归档格式。没有内部存储的文件名,这就是为什么通常名为
x.y
的文件被压缩为
x.y.gz
的原因。实际上,gzip头中可能存储并且通常存储一个文件名,但在解压缩时默认不使用它。
public void gzipFile(String fromFile, String toFile) throws IOException {



    GZIPOutputStream out = null;
    BufferedInputStream in = null;


    try {
        // Open the input file
        in = new BufferedInputStream(new FileInputStream(fromFile));

        // Create the GZIP output stream
        out = new GZIPOutputStream(new BufferedOutputStream(new FileOutputStream(toFile)));

        // Transfer bytes from the input file to the GZIP output stream
        byte[] buffer = new byte[1024];
        int len;
        while ((len = in.read(buffer)) != -1) {
            out.write(buffer, 0, len);
        }
        //Complete the entry
        out.flush();
        in.close();


        File newFile = new File(toFile.replace(".log", ""));
        System.out.println(newFile);
        File file = new File(toFile);
        file.renameTo(newFile);
    } catch (IOException e) {
        // log and return false
        e.printStackTrace();
    } finally {
        try {
            if (in != null) {
                in.close();
            }
            if (out != null) {
                // Complete the GZIP file
                out.finish();
                out.close();
            }
        } catch (IOException ignore) {
        }
    }

}