java压缩中文文件名乱码,只设置编码也不管用

在使用Java压缩本地文件或者服务器文件提供下载时,想必大家都会遇压缩包里的中文名的文件名乱码的问题。是的,在使用Java来处理各种各样的文件、图片等IO数据流的时候经常会遇到乱码的问题。

 

用Java来实现压缩本地文件,通常是使用    org.apache.tools.zip.ZipOutputStream 类实现的,Demo 代码如下:

public static void zipFilesToZipFile(String dirPath, File file,
			ZipOutputStream zouts) {
		zouts.setEncoding("UTF-8");
		FileInputStream fin = null;
		ZipEntry entry = null;
		// 创建复制缓冲区
		byte[] buf = new byte[4096];
		int readByte = 0;
		if (file.isFile()) {
			try {
				// 创建一个文件输入流
				fin = new FileInputStream(file);
				// 创建一个ZipEntry
				entry = new ZipEntry(getEntryName(dirPath, file));
				// 存储信息到压缩文件
				zouts.putNextEntry(entry);        
                //此处添加乱码设置
                
				// 复制字节到压缩文件
				while ((readByte = fin.read(buf)) != -1) {
					zouts.write(buf, 0, readByte);
				}
				
				zouts.closeEntry();
				fin.close();
				System.out.println("添加文件 " + file.getAbsolutePath()
						+ " 到zip文件中!");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}
如果直接按上面的代码来执行压缩以中文为文件名的文件的话那就会出现乱码,

java压缩中文文件名乱码,只设置编码也不管用_第1张图片

 

那么设置了  ZipOutputStream 的编码为“UTF-8” 就可以了吗?还是不可以,那么该怎么办呢?

还需要设置一个属性那就是:

将被压缩的文件或文件夹实体 设置UnixMode为 664 ,代码如下:
entry.setUnixMode(644);

这样处理后,就不乱码了,大家可能试试!最终的代码如下:

public static void zipFilesToZipFile(String dirPath, File file,
			ZipOutputStream zouts) {
		zouts.setEncoding("UTF-8");
		FileInputStream fin = null;
		ZipEntry entry = null;
		// 创建复制缓冲区
		byte[] buf = new byte[4096];
		int readByte = 0;
		if (file.isFile()) {
			try {
				// 创建一个文件输入流
				fin = new FileInputStream(file);
				// 创建一个ZipEntry
				entry = new ZipEntry(getEntryName(dirPath, file));
				// 存储信息到压缩文件
				zouts.putNextEntry(entry);
				entry.setUnixMode(644);
				// 复制字节到压缩文件
				while ((readByte = fin.read(buf)) != -1) {
					zouts.write(buf, 0, readByte);
				}
				zouts.setEncoding("gbk");
				zouts.closeEntry();
				fin.close();
				System.out.println("添加文件 " + file.getAbsolutePath()
						+ " 到zip文件中!");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}

还特别注意,如果是目录的话需要设置为 755模式: 

entry.setUnixMode(755);

希望对你有所帮助,谢谢关注!

你可能感兴趣的:(Java,java,乱码,压缩)