解壓.zip,.tar.gz文件到指定目錄,重命名文件

1.解壓文件到指定目錄java

/**
     * 解壓文件到指定目錄
     * zipFile:要解壓的文件
     * descDir:解壓到哪一個文件
     * 
     */
    @SuppressWarnings("rawtypes")
    public static void unZipFiles(File zipFile,String descDir)throws IOException
    {
      File pathFile = new File(descDir);
      if(!pathFile.exists())
      {
        pathFile.mkdirs();
      }
      //解決zip文件中有中文目錄或者中文文件
      ZipFile zip = new ZipFile(zipFile, Charset.forName("GBK"));
      for(Enumeration entries = zip.entries(); entries.hasMoreElements();)
      {
        ZipEntry entry = (ZipEntry)entries.nextElement();
        String zipEntryName = entry.getName();
        InputStream in = zip.getInputStream(entry);
        String outPath = (descDir+zipEntryName).replaceAll("\\*", "/");;
        //判斷路徑是否存在,不存在則建立文件路徑
        File file = new File(outPath.substring(0, outPath.lastIndexOf('/')));
        if(!file.exists())
        {
          file.mkdirs();
        }
        //判斷文件全路徑是否爲文件夾,若是是上面已經上傳,不須要解壓
        if(new File(outPath).isDirectory())
        {
          continue;
        }
        //輸出文件路徑信息
        System.out.println(outPath);
        OutputStream out = new FileOutputStream(outPath);
        byte[] buf1 = new byte[1024];
        int len;
        while((len=in.read(buf1))>0)
        {
          out.write(buf1,0,len);
        }
        in.close();
        out.close();
      }
      System.out.println("******************解壓完畢********************");
    }

解壓tar.gz 文件apache

package com.hou;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.GZIPInputStream;

import org.apache.tools.tar.TarEntry;
import org.apache.tools.tar.TarInputStream;

/**
 * 解壓tar.gz 文件 
 * ClassName: Test01 
 * @Description: TODO
 * @author HJJ
 * @date 2018年10月17日
 */
public class Test01 {
    
    public static void main(String[] args) {
        File file=new File("D:/home/app/data/tiantai/new/pred_2018-10-15.tar.gz");
        String str="D:/home/app/data/tiantai/new/";
        try {
            unTarGz(file,str);
            System.out.println("解壓成功");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
  //------------------------------------------------------------------------------------------------------
    /** 
     * 解壓tar.gz 文件 
     * @param file 要解壓的tar.gz文件對象 
     * @param outputDir 要解壓到某個指定的目錄下 
     * @throws IOException 
     */  
    public static void unTarGz(File file,String outputDir) throws IOException{  
        TarInputStream tarIn = null;  
        try{  
            tarIn = new TarInputStream(new GZIPInputStream(  
                    new BufferedInputStream(new FileInputStream(file))),  
                    1024 * 2);  
              
            createDirectory(outputDir,null);//建立輸出目錄  

            TarEntry entry = null;  
            while( (entry = tarIn.getNextEntry()) != null ){  
                  
                if(entry.isDirectory()){//是目錄
                    entry.getName();
                    createDirectory(outputDir,entry.getName());//建立空目錄  
                }else{//是文件
                    File tmpFile = new File(outputDir + "/" + entry.getName());  
                    createDirectory(tmpFile.getParent() + "/",null);//建立輸出目錄  
                    OutputStream out = null;  
                    try{  
                        out = new FileOutputStream(tmpFile);  
                        int length = 0;  
                          
                        byte[] b = new byte[2048];  
                          
                        while((length = tarIn.read(b)) != -1){  
                            out.write(b, 0, length);  
                        }  
                      
                    }catch(IOException ex){  
                        throw ex;  
                    }finally{  
                          
                        if(out!=null)  
                            out.close();  
                    }  
                }
            }  
        }catch(IOException ex){  
            throw new IOException("解壓歸檔文件出現異常",ex);  
        } finally{  
            try{  
                if(tarIn != null){  
                    tarIn.close();  
                }  
            }catch(IOException ex){  
                throw new IOException("關閉tarFile出現異常",ex);  
            }  
        }  
    }
    
    /** 
     * 構建目錄 
     * @param outputDir 
     * @param subDir 
     */  
    public static void createDirectory(String outputDir,String subDir){     
        File file = new File(outputDir);  
        if(!(subDir == null || subDir.trim().equals(""))){//子目錄不爲空  
            file = new File(outputDir + "/" + subDir);  
        }  
        if(!file.exists()){  
              if(!file.getParentFile().exists())
                  file.getParentFile().mkdirs();
            file.mkdirs();  
        }  
    }

}

3.解壓指定目錄下的zip文件緩存

/**
     * 解壓指定目錄下的zip文件
     * @param checkPath 檢測目錄,先從緩存中取,若是緩存中不存在,再從配置文件中提取
     * @param fileName 待解壓的zip文件
     * @throws Exception
     */
    private static void unzip(String checkPath,String fileName) throws Exception {

        if (checkPath.startsWith("~")) {
            checkPath = System.getProperty("user.home")+ checkPath.substring(1);
        }

//        final String currentPath = checkPath;
        final String currentPath = "D:/home/app/data/tiantai/new/";

//        String fileRoot = checkPath + File.separator +  fileName;  //zip文件路徑
        String fileRoot = "D:/home/app/data/tiantai/new/QUNAR_ONE_COMMON_PRYPAY_1539141468602.zip";  //zip文件路徑
        //System.out.println("解壓的zip文件 fileRoot:" + fileRoot);
        System.out.println("解壓的zip文件 fileRoot:" + fileRoot);

        FileSystem fs = FileSystems.newFileSystem(Paths.get(fileRoot),null);

        Files.walkFileTree(fs.getPath("/"),new SimpleFileVisitor<Path>(){ //遍歷文件系統時,可獲取文件屬性
            /**
             * Invoked for a file in a directory.
             * <p>
             * <p> Unless overridden, this method returns {@link FileVisitResult#CONTINUE
             * CONTINUE}.
             *
             * @param file
             * @param attrs
             */
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                Path destPath = Paths.get(currentPath,file.toString());
                Files.deleteIfExists(destPath);//若是目標文件已經存在,則刪除
                Files.createDirectories(destPath.getParent());//建立文件的父目錄,無論是文件仍是目錄
                Files.move(file, destPath);

                return FileVisitResult.CONTINUE;
            }
        });

        fs.close();//關閉文件系統

        //文件解壓成功後,刪除zip文件
        File delZipFile = new File(fileRoot);
        if(delZipFile.exists() && delZipFile.isFile()){
            boolean d = delZipFile.delete();
            if(d){
               // System.out.println(fileRoot + " 文件已刪除...");
                System.out.println((fileRoot + " 文件已刪除..."));
                
            }

        }

    }

4.app

public static void Decompressing2() throws IOException {
//        String path = "D:/home/app/data/tiantai/new/";
        String path = "D:/home/app/data/tiantai/new/";
        ZipEntry zipEntry = null;
        try {
            // ZipInputStream讀取壓縮文件
            FileInputStream file=new FileInputStream(new File(path+"QUNAR_ONE_COMMON_PRYPAY_1539679543536.zip"));
//            ZipFile zipFile = new ZipFile(new File(path+"QUNAR_ONE_COMMON_PRYPAY_1539141468602.zip"),Charset.forName("gbk")) ;
            ZipInputStream zipInputStream = new ZipInputStream(file);
            // 寫入到緩衝流中
            BufferedInputStream bufferedInputStream = new BufferedInputStream(zipInputStream);
            File fileOut = null;
            // 讀取壓縮文件中的一個文件
//            zipEntry = zipInputStream.getNextEntry();
            while ((zipEntry = zipInputStream.getNextEntry()) != null) {
                // 若當前zipEntry是一個文件夾
                if (zipEntry.isDirectory()) {
                    fileOut = new File(path + "//" +zipEntry.getName());
                    // 在指定路徑下建立文件夾
                    if (!fileOut.exists()) {
                        fileOut.mkdirs();                       
                    }
                //如果文件
                } else {
                    // 原文件名與指定路徑建立File對象(解壓後文件的對象)
                    fileOut = new File(path, zipEntry.getName());
                    try(
                            FileOutputStream fileOutputStream = new FileOutputStream(fileOut);
                            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);){
                        //將文件寫入到指定file中
                        int b = 0;
                        while ((b = bufferedInputStream.read()) != -1) {
                            bufferedOutputStream.write(b);
                    }
                    }catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

 5less

readByZipInputStream("D:/home/app/data/tiantai/new/QUNAR_ONE_COMMON_PRYPAY_1539065367654.zip", "d:/");

public static void readByZipInputStream(String archive, String decompressDir)  
            throws FileNotFoundException, IOException {  
        BufferedInputStream bi;  
          
        ZipFile zf = new ZipFile(archive, Charset.forName("gbk"));//支持中文  
  
        Enumeration e = zf.entries();  
        while (e.hasMoreElements()) {  
            ZipEntry ze2 = (ZipEntry) e.nextElement();  
            String entryName = ze2.getName();  
            String path = decompressDir + "/" + entryName;  
            if (ze2.isDirectory()) {  
                System.out.println("正在建立解壓目錄 - " + entryName);  
                File decompressDirFile = new File(path);  
                if (!decompressDirFile.exists()) {  
                    decompressDirFile.mkdirs();  
                }  
            } else {  
                System.out.println("正在建立解壓文件 - " + entryName);  
                String fileDir = path.substring(0, path.lastIndexOf("/"));  
                File fileDirFile = new File(fileDir);  
                if (!fileDirFile.exists()) {  
                    fileDirFile.mkdirs();  
                }  
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(  
                        decompressDir + "/" + entryName));  
  
                bi = new BufferedInputStream(zf.getInputStream(ze2));  
                byte[] readContent = new byte[1024];  
                int readCount = bi.read(readContent);  
                while (readCount != -1) {  
                    bos.write(readContent, 0, readCount);  
                    readCount = bi.read(readContent);  
                }  
                bos.close();  
            }  
        }  
        zf.close();  
    }

6.修改文件名ide

/**
     * 經過文件路徑直接修改文件名
     * @param filePath 須要修改的文件的完整路徑
     * @param newFileName 須要修改的文件的名稱
     * @return
     */
    public static String FixFileName(String filePath, String newFileName) {
        File f = new File(filePath);
        if (!f.exists()) { // 判斷原文件是否存在
            return null;
        }
        
        newFileName = newFileName.trim();
        if ("".equals(newFileName) || newFileName == null) // 文件名不能爲空
            return null;
        
        String newFilePath = null;
        if (f.isDirectory()) { // 判斷是否爲文件夾
            newFilePath = filePath.substring(0, filePath.lastIndexOf("/")) + "/" + newFileName;
        } else {
            newFilePath = filePath.substring(0, filePath.lastIndexOf("/"))+ "/"  + newFileName ;
        }
        File nf = new File(newFilePath);
        if (!f.exists()) { // 判斷須要修改成的文件是否存在(防止文件名衝突)
            return null;
        }
        
        try {
            f.renameTo(nf); // 修改文件名
        } catch(Exception err) {
            err.printStackTrace();
            return null;
        }
        
        return newFilePath;
    }
相關文章
相關標籤/搜索