java压缩文件内后是乱码,怎么办
/**
* 压缩多个文件
*
@param filePath[] 文件路径数组
*
@param targetFilePath 压缩后文件路径
*/
public static void createZipMoreFile(String filePath[],
String targetFilePath) {
try {
FileOutputStream fos = new FileOutputStream(targetFilePath);
CheckedOutputStream cos = new CheckedOutputStream(fos, new CRC32());
ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(
cos));
for (int i = 0; i < filePath.length; i++) {
// 逐个将文件写入到br,然后再逐个从br读到压缩文件中。
BufferedReader br = new BufferedReader(new FileReader(
filePath[i]));
filePath[i] = filePath[i].replaceAll("\\", "/");
zos.putNextEntry(new ZipEntry(filePath[i].substring(filePath[i]
.lastIndexOf("/") + 1)));
int c;
while ((c = br.read()) != -1)
zos.write(c);
br.close();
}
zos.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
代码贴出来了,另外我引用的jar包是import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
这样有什么办法没?
如果你对这篇文章有疑问,欢迎到本站 社区 发帖提问或使用手Q扫描下方二维码加群参与讨论,获取更多帮助。

评论(7)

引用来自“甘薯”的评论
以下代码已测试通过无误
try { FileOutputStream fos = new FileOutputStream(targetFilePath); CheckedOutputStream cos = new CheckedOutputStream(fos, new CRC32()); ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream( cos)); for (int i = 0; i < filePath.length; i++) { // 逐个将文件写入到br,然后再逐个从br读到压缩文件中。 // BufferedReader br = new BufferedReader(new FileReader( // filePath[i])); FileInputStream br = new FileInputStream(new File( "c:\test\" + filePath[i])); filePath[i] = filePath[i].replaceAll("\\", "/"); zos.putNextEntry(new ZipEntry(filePath[i].substring(filePath[i] .lastIndexOf("/") + 1))); // int c; byte[] b = new byte[1024]; int len = 0; while ((len = br.read(b)) != -1) { //.re.read()) != -1) byte [] c = b; if (len != b.length) { c = Arrays.copyOf(b, len); } zos.write(c); } br.close(); } zos.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }


以下代码已测试通过无误
try { FileOutputStream fos = new FileOutputStream(targetFilePath); CheckedOutputStream cos = new CheckedOutputStream(fos, new CRC32()); ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream( cos)); for (int i = 0; i < filePath.length; i++) { // 逐个将文件写入到br,然后再逐个从br读到压缩文件中。 // BufferedReader br = new BufferedReader(new FileReader( // filePath[i])); FileInputStream br = new FileInputStream(new File( "c:\test\" + filePath[i])); filePath[i] = filePath[i].replaceAll("\\", "/"); zos.putNextEntry(new ZipEntry(filePath[i].substring(filePath[i] .lastIndexOf("/") + 1))); // int c; byte[] b = new byte[1024]; int len = 0; while ((len = br.read(b)) != -1) { //.re.read()) != -1) byte [] c = b; if (len != b.length) { c = Arrays.copyOf(b, len); } zos.write(c); } br.close(); } zos.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }
发布评论
需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。