本文共 2979 字,大约阅读时间需要 9 分钟。
- <span style="font-size:18px;">
- public final class ZipUtil {
-
-
- public static void unZip(String unZipfile, String destFile) {
- FileOutputStream fileOut;
- File file;
- InputStream inputStream;
- byte[] buf = new byte[1024*4];
- try {
-
- ZipFile zipFile = new ZipFile(unZipfile, "GBK");
-
- for (@SuppressWarnings("unchecked")
- Enumeration<ZipEntry> entries = zipFile.getEntries(); entries
- .hasMoreElements();) {
- ZipEntry entry = entries.nextElement();
-
- file = new File(destFile+File.separator+entry.getName());
-
- if (entry.isDirectory()) {
- file.mkdirs();
- } else {
-
- File parent = file.getParentFile();
- if (!parent.exists()) {
- parent.mkdirs();
- }
-
- inputStream = zipFile.getInputStream(entry);
-
- fileOut = new FileOutputStream(file);
- int length = 0;
-
- while ((length = inputStream.read(buf)) > 0) {
- fileOut.write(buf, 0, length);
- }
- fileOut.close();
- inputStream.close();
- }
- }
- zipFile.close();
-
- File zipfile = new File(unZipfile);
- if(zipfile.exists()){
- zipfile.delete();
- }
- } catch (IOException ioe) {
- ioe.printStackTrace();
- }
- }
-
-
-
-
- public static void toZip(String filepath,String savepath) throws Exception{
- File file = new File(filepath);
- if(file.exists()){
-
- if(StringUtils.isBlank(savepath)){
- savepath = filepath+".zip";
- }else{
- savepath = savepath+".zip";
- }
- ZipOutputStream outPut = new ZipOutputStream(new FileOutputStream(new File(savepath)));
- outPut.setEncoding("GBK");
- createZip(outPut,file.listFiles(),null);
- outPut.flush();
- outPut.close();
- }else{
-
- throw new RuntimeException("Err :not found file exception:"+filepath);
- }
- }
-
- private static void createZip(org.apache.tools.zip.ZipOutputStream outPut,File[] listFiles,String fuPath) throws Exception {
- for(File f : listFiles){
- String name = fuPath==null?f.getName():fuPath+"/"+f.getName();;
- if(f.isDirectory()){
- outPut.putNextEntry(new ZipEntry(name+"/"));
- createZip(outPut,f.listFiles(),name);
- }else{
- outPut.putNextEntry(new ZipEntry(name));
- InputStream is = new FileInputStream(f);
- byte[] bys = new byte[1024];
- int len = 0;
- while((len = is.read(bys))!=-1)
- outPut.write(bys, 0, len);
- is.close();
- outPut.flush();
- }
- }
- }
-
-
- public static void fileChannelCopy(File fromfile, File tofile) {
- FileInputStream fi = null;
- FileOutputStream fo = null;
- FileChannel in = null;
- FileChannel out = null;
- try {
- fi = new FileInputStream(fromfile);
- fo = new FileOutputStream(tofile);
- in = fi.getChannel();
- out = fo.getChannel();
- in.transferTo(0, in.size(), out);
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- try {
- fi.close();
- in.close();
- fo.close();
- out.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- }</span>
转载于:https://www.cnblogs.com/challengeof/p/4281840.html