我试图用缓冲的输入流读取一个txt文件,并用GZIP压缩它,它可以工作。但是,当我尝试使用zip提取压缩文件时,该文件似乎是无法读取的二进制格式,如何解决此问题?以下是我的代码:

public static void main(String[] args) {
    compressWithGZIP(SAVE_PATH2, SAVE_PATH3);
    //uncompressWithGZIP(SAVE_PATH3 + "compressed.gz", SAVE_PATH4);
}

private static void uncompressWithGZIP(String oripath, String outputPath) {
    BufferedInputStream bi = null;
    BufferedOutputStream bo = null;
    try {
        bi = new BufferedInputStream(new GZIPInputStream(
                new FileInputStream(oripath)));
        bo = new BufferedOutputStream(new FileOutputStream(outputPath));
        int c;
        while ((c = bi.read()) != -1) {
            bo.write(c);
        }
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        try {
            if (bi != null) {
                bi.close();
            }
            if (bo != null) {
                bo.close();
            }
        } catch (Exception e) {
            e.printStackTrace();

        }
    }
}

private static void compressWithGZIP(String filePath, String outputPath) {
    if (outputPath == null || outputPath.isEmpty()
            || !outputPath.endsWith(".gz")) {
        outputPath += "compressed.gz";
    }

    BufferedReader br = null;
    BufferedOutputStream bo = null;
    try {
        br = new BufferedReader(new FileReader(filePath));
        bo = new BufferedOutputStream(new GZIPOutputStream(
                new FileOutputStream(outputPath)));
        int c;
        while ((c = br.read()) != -1) {
            bo.write(c);
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (br != null) {
                br.close();
            }
            if (bo != null) {
                bo.close();
            }
        } catch (Exception e) {
            e.printStackTrace();

        }
    }

}

最佳答案

经典错误。

做。不。永远使用。一位读者。至。读。二进制数据..

Reader使用字符解码过程将从文件中读取的数据解释为潜在字符。 Java定义Reader和InputStream以及Writer和OutputStream的原因是有原因的。

如果处理二进制数据,请使用InputStream和OutputStream。永远不要读者或作家。

换句话说,您的问题在这里:

    br = new BufferedReader(new FileReader(filePath));
    bo = new BufferedOutputStream(new GZIPOutputStream(
            new FileOutputStream(outputPath)));


使用InputStream而不是Reader从源文件读取。

10-06 05:48
查看更多