gpt4 book ai didi

java - 在java中使用GZIP压缩文件

转载 作者:行者123 更新时间:2023-12-01 21:59:15 27 4
gpt4 key购买 nike

我尝试使用缓冲输入流读取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)从源文件中读取。

关于java - 在java中使用GZIP压缩文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33876290/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com