java解压缩文件,解决中文乱码。

来源:互联网 发布:工作任务安排软件 编辑:程序博客网 时间:2024/05/02 15:42

import java.io.File;import java.io.FileOutputStream;import java.io.InputStream;import java.util.Enumeration;import org.apache.tools.ant.Project;import org.apache.tools.ant.types.FileSet;import org.apache.tools.zip.ZipEntry;import org.apache.tools.zip.ZipFile;/** * @author 王泽浩 *  *         E-mail: 1028625100@qq.com *  * @version v1.1 *  *          创建时间:2015年1月4日 上午11:18:47 *           *          使用ant工具包可以解决解压缩文件中文乱码问题,需要引入ant-x.x.x.jar(项目使用的是ant-1.9.4.jar) */public class Zip {/** * 解压zip *  * @param path *            解压到的目录("D:/test") *  * @param zipFile *  *            压缩文件(new ZipFile(new File("D:/test.zip"))) *  * @return boolean 返回true时解压成功,false择解压失败 */public static boolean unZip(String path, ZipFile zipFile) {FileOutputStream fileOutputStream = null;InputStream inputStream = null;File file = null;try {int bufSize = 512;byte[] buf = new byte[bufSize];int readedBytes;for (Enumeration<ZipEntry> entries = zipFile.getEntries(); entries.hasMoreElements();) {ZipEntry entry = entries.nextElement();file = new File(path + "/" + entry.getName());if (entry.isDirectory()) {file.mkdirs();} else {File parent = file.getParentFile();if (!parent.exists()) {parent.mkdirs();}inputStream = zipFile.getInputStream(entry);fileOutputStream = new FileOutputStream(file);while ((readedBytes = inputStream.read(buf)) > 0) {fileOutputStream.write(buf, 0, readedBytes);}close(fileOutputStream, inputStream);}}zipFile.close();return true;} catch (Exception e) {e.printStackTrace();return false;} finally {close(fileOutputStream, inputStream);}}/** * 压缩文件 *  * @param src *            将要压缩的文件夹(new File("D:/test/")) *  * @param dest *            将压缩文件夹存储到什么位置(new File(D:/test.zip)) *  * @return boolean 返回true时压缩成功,false择压缩失败 */public static boolean zip(File src, File dest) {try {Project prj = new Project();org.apache.tools.ant.taskdefs.Zip zip = new org.apache.tools.ant.taskdefs.Zip();zip.setProject(prj);zip.setDestFile(dest);FileSet fileSet = new FileSet();fileSet.setProject(prj);if (src.isFile()) {fileSet.setFile(src);} else {fileSet.setDir(src);}zip.addFileset(fileSet);zip.execute();return true;} catch (Exception e) {e.printStackTrace();return false;}}/** * 关闭流 *  * @param autoCloseables */public static void close(AutoCloseable... autoCloseables) {try {if (autoCloseables != null) {for (AutoCloseable autoCloseable : autoCloseables) {autoCloseable.close();}}} catch (Exception e) {e.printStackTrace();}}}








0 0
原创粉丝点击