java File工具类 FileUtils

package com.wqh.fsrm.common.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream;
import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream;
import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream;
import org.apache.commons.compress.utils.IOUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;

/**
 * 压缩文件 操作
 * @author wqh
 *
 */
public class FileCompressUtils {

	public static void main(String args[]) throws Exception {
		//System.out.println();
//		uncompress("D:/1.zip","D:\\");
//		File file = new File("D:/1.zip");
//		ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(file));
//
//		zip("D:/1.txt", file, zos, true, true);

		System.out.println(getZipFileNameList("D:/2.zip"));

		//System.out.println(unZip("F:\\fileupload\\dna-sample.zip", "F:\\fileupload\\"));
		//System.out.println(unTar("F:\\fileupload\\中文test.tar", "F:\\fileupload\\"));

		//System.out.println(unBZip2("F:\\fileupload\\中文test.xml.bz2", "F:\\fileupload\\"));
		//System.out.println(unTarBZip2("F:\\fileupload\\中文test.tar.bz2", "F:\\fileupload\\"));

		//System.out.println(unGZ("e:/haodu_20151113.txt.gz", "e:/output/"));
		//System.out.println(unTarGZ("F:\\fileupload\\all.tar.gz", "F:\\fileupload\\"));
	}


	/**
	 * 读取压缩文件
	 * @param zipFilePath  压缩文件路径
	 * @param inFileName   压缩文件里面源文件名称
	 * @return
	 * @throws Exception
	 */
	public static String readFileInZip(String zipFilePath, String inFileName) throws Exception {
		ZipFile zf =new ZipFile(new File(zipFilePath));
		StringBuffer sb=new StringBuffer();
		BufferedReader br=new BufferedReader(new InputStreamReader(zf.getInputStream(zf.getEntry(inFileName))));
		String s;
		while ((s = br.readLine()) != null)
			sb.append(s);
		br.close();
		return sb.toString();
	}
	/**
	 * 读取压缩文件内容
	 * @param zipFilePath  压缩文件路径
	 * @param inFileName   压缩文件里面源文件名称
	 * @return
	 */
	public static String readFileContentInZip(String zipFilePath, String inFileName) {
		String t = "";
		String jarFilePath = zipFilePath;
		String fileName = inFileName;
		File jarFile = new File(jarFilePath);
		if (jarFile.exists()) {
			try {
				ZipFile zipFile = new ZipFile(jarFile);
				ZipEntry tipEnty = zipFile.getEntry(fileName);
				ZipInputStream zin = new ZipInputStream(new FileInputStream(jarFilePath));
				ZipEntry entry;
				while ((entry = zin.getNextEntry()) != null) {
					if (entry.getName().equals(fileName)) {
						BufferedReader in = new BufferedReader(new InputStreamReader(zin,Charset.forName("utf-8")));
						String s = "";
						while ((s = in.readLine()) != null) {
							t += s + "\n";
						}
					}// end if entry
					zin.closeEntry();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}// end if jarFile
		return t;
	}

	/**
	 * 通过编码读取压缩文件
	 * @param zipFilePath  压缩文件路径
	 * @param inFileName   压缩文件里面源文件名称
	 * @param inEncode     编码
	 * @return
	 * @throws Exception
	 */
	public static String readFileInZipByEncode(String zipFilePath, String inFileName,String inEncode) throws Exception {
		inEncode=(inEncode==null||"".equals(inEncode))?"utf-8":inEncode;
		ZipFile zf =new ZipFile(new File(zipFilePath));
		StringBuffer sb=new StringBuffer();
		BufferedReader br=new BufferedReader(new InputStreamReader(zf.getInputStream(zf.getEntry(inFileName)),Charset.forName(inEncode)));
		String s;
		while ((s = br.readLine()) != null)
			sb.append(s);
		br.close();
		return sb.toString();
	}


	/**
	 * 获取压缩文件文件列表
	 * @param zipname   //压缩文件路径
	 * @return
	 * @throws Exception
	 */
	public static List<String> getZipFileNameList(String zipname) throws Exception{
		List<String> fileList = new ArrayList<String>();
		ZipInputStream zin = new ZipInputStream(new FileInputStream(zipname));
		ZipEntry entry;
		while ((entry = zin.getNextEntry()) != null) {
			fileList.add(entry.getName());
			zin.closeEntry();
		}
		zin.close();
		return fileList;
	}

	/**
	 *
	 * @param inFileOrFolderName
	 * @param outCompressFileName
	 * @throws IOException
	 */
	public static void compress(String inFileOrFolderName,String outCompressFileName) throws IOException {
		ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(outCompressFileName));
		zos.setComment("");
		zip(inFileOrFolderName, new File(outCompressFileName), zos, true, true);
		zos.close();
	}
	/**
	 * 压缩成zip
	 * @param path
	 * @param basePath
	 * @param zo
	 * @param isRecursive
	 * @param isOutBlankDir
	 * @throws IOException
	 */
	public static void zip(String path, File basePath, ZipOutputStream zo, boolean isRecursive, boolean isOutBlankDir) throws IOException {
		File inFile = new File(path);
		File[] files = new File[0];
		if(inFile.isDirectory()) {    //directory
			files = inFile.listFiles();
		} else if(inFile.isFile()) {    //file
			files = new File[1];
			files[0] = inFile;
		}
		byte[] buf = new byte[1024];
		int len;
		for(int i=0; i<files.length; i++) {
			String pathName = "";
			if(basePath != null) {
				if(basePath.isDirectory()) {
					pathName = files[i].getPath().substring(basePath.getPath().length()+1);
				} else {//file
					pathName = files[i].getPath().substring(basePath.getParent().length()+1);
				}
			} else {
				pathName = files[i].getName();
			}
			pathName=(pathName.substring(pathName.indexOf("\\", 0)+1));
			if(files[i].isDirectory()) {
				if(isOutBlankDir && basePath != null) {
					zo.putNextEntry(new ZipEntry(pathName+"/"));
				}
				if(isRecursive) {
					zip(files[i].getPath(), basePath, zo, isRecursive, isOutBlankDir);
				}
			} else {
				FileInputStream fin = new FileInputStream(files[i]);
				zo.putNextEntry(new ZipEntry(pathName));
				while((len=fin.read(buf))>0) {
					zo.write(buf,0,len);
				}
				fin.close();
			}
		}
	}

	/**
	 * 解压
	 * @param inFileName  //压缩文件路径
	 * @param outPath     //输出文件路径
	 * @throws Exception
	 */
	public static void uncompress(String inFileName,String outPath) throws Exception {
		File file = new File(inFileName);  // source compress file
		ZipFile zipFile = new ZipFile(file);
		ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(file));
		ZipEntry zipEntry = null;
		while ((zipEntry = zipInputStream.getNextEntry()) != null) {
			String fileName = zipEntry.getName();
			File temp = new File(outPath + fileName);
			if (!temp.getParentFile().exists())
				temp.getParentFile().mkdirs();
			OutputStream os = new FileOutputStream(temp);
			InputStream is = zipFile.getInputStream(zipEntry);
			int len = 0;
			while ((len = is.read()) != -1)
				os.write(len);
			os.close();
			is.close();
		}
		zipInputStream.close();
	}


	public static int BUFFER_SIZE = 2048;

	/**
	 * 解压成tar 格式
	 * @param inputStream
	 * @param destDir
	 * @return
	 * @throws Exception
	 */
	private static List<String> unTar(InputStream inputStream, String destDir) throws Exception {
		List<String> fileNames = new ArrayList<String>();
		TarArchiveInputStream tarIn = new TarArchiveInputStream(inputStream, BUFFER_SIZE);
		TarArchiveEntry entry = null;
		try {
			while ((entry = tarIn.getNextTarEntry()) != null) {
				fileNames.add(entry.getName());
				if (entry.isDirectory()) {//是目�?
					createDirectory(destDir, entry.getName());//创建空目�?
				} else {//是文�?
					File tmpFile = new File(destDir + File.separator + entry.getName());
					createDirectory(tmpFile.getParent() + File.separator, 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);
						}
					} finally {
						IOUtils.closeQuietly(out);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		} finally {
			IOUtils.closeQuietly(tarIn);
		}

		return fileNames;
	}

	/**
	 * 参数为 string 类型
	 * @param tarFile
	 * @param destDir
	 * @return
	 * @throws Exception
	 */
	public static List<String> unTar(String tarFile, String destDir) throws Exception {
		File file = new File(tarFile);
		return unTar(file, destDir);
	}
	/**
	 * 参数为 File 类型
	 * @param tarFile
	 * @param destDir
	 * @return
	 * @throws Exception
	 */

	public static List<String> unTar(File tarFile, String destDir) throws Exception {
		if(StringUtils.isBlank(destDir)) {
			destDir = tarFile.getParent();
		}
		destDir = destDir.endsWith(File.separator) ? destDir : destDir + File.separator;
		return unTar(new FileInputStream(tarFile), destDir);
	}

	public static List<String> unTarBZip2(File tarFile,String destDir) throws Exception{
		if(StringUtils.isBlank(destDir)) {
			destDir = tarFile.getParent();
		}
		destDir = destDir.endsWith(File.separator) ? destDir : destDir + File.separator;
		return unTar(new BZip2CompressorInputStream(new FileInputStream(tarFile)), destDir);
	}

	public static List<String> unTarBZip2(String file,String destDir) throws Exception{
		File tarFile = new File(file);
		return unTarBZip2(tarFile, destDir);
	}

	public static List<String> unBZip2(String bzip2File, String destDir) throws IOException {
		File file = new File(bzip2File);
		return unBZip2(file, destDir);
	}

	/**
	 * 解压成 zip 类型
	 * @param srcFile
	 * @param destDir
	 * @return
	 * @throws IOException
	 */
	public static List<String> unBZip2(File srcFile, String destDir) throws IOException {
		if(StringUtils.isBlank(destDir)) {
			destDir = srcFile.getParent();
		}
		destDir = destDir.endsWith(File.separator) ? destDir : destDir + File.separator;
		List<String> fileNames = new ArrayList<String>();
		InputStream is = null;
		OutputStream os = null;
		try {
			File destFile = new File(destDir, FilenameUtils.getBaseName(srcFile.toString()));
			fileNames.add(FilenameUtils.getBaseName(srcFile.toString()));
			is = new BZip2CompressorInputStream(new BufferedInputStream(new FileInputStream(srcFile), BUFFER_SIZE));
			os = new BufferedOutputStream(new FileOutputStream(destFile), BUFFER_SIZE);
			IOUtils.copy(is, os);
		} finally {
			IOUtils.closeQuietly(os);
			IOUtils.closeQuietly(is);
		}
		return fileNames;
	}


	public static List<String> unGZ(String gzFile, String destDir) throws IOException {
		File file = new File(gzFile);
		return unGZ(file, destDir);
	}

	/**
	 * 解压成gz 类型
	 * @param srcFile
	 * @param destDir
	 * @return
	 * @throws IOException
	 */
	public static List<String> unGZ(File srcFile, String destDir) throws IOException {
		if(StringUtils.isBlank(destDir)) {
			destDir = srcFile.getParent();
		}
		destDir = destDir.endsWith(File.separator) ? destDir : destDir + File.separator;
		List<String> fileNames = new ArrayList<String>();
		InputStream is = null;
		OutputStream os = null;
		try {
			File destFile = new File(destDir, FilenameUtils.getBaseName(srcFile.toString()));
			fileNames.add(FilenameUtils.getBaseName(srcFile.toString()));
			is = new GzipCompressorInputStream(new BufferedInputStream(new FileInputStream(srcFile), BUFFER_SIZE));
			os = new BufferedOutputStream(new FileOutputStream(destFile), BUFFER_SIZE);
			IOUtils.copy(is, os);
		} finally {
			IOUtils.closeQuietly(os);
			IOUtils.closeQuietly(is);
		}
		return fileNames;
	}

	public static List<String> unTarGZ(File tarFile,String destDir) throws Exception{
		if(StringUtils.isBlank(destDir)) {
			destDir = tarFile.getParent();
		}
		destDir = destDir.endsWith(File.separator) ? destDir : destDir + File.separator;
		return unTar(new GzipCompressorInputStream(new FileInputStream(tarFile)), destDir);
	}

	public static List<String> unTarGZ(String file,String destDir) throws Exception{
		File tarFile = new File(file);
		return unTarGZ(tarFile, destDir);
	}

	/**
	 * 创建文件夹
	 * @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 + File.separator + subDir);
		}
		if(!file.exists()){
			file.mkdirs();
		}
	}

	/**
	 * 解压成zip
	 * @param zipfile
	 * @param destDir
	 * @return
	 * @throws Exception
	 */
	public static List<String> unZip(File zipfile, String destDir) throws Exception {
		if(StringUtils.isBlank(destDir)) {
			destDir = zipfile.getParent();
		}
		destDir = destDir.endsWith(File.separator) ? destDir : destDir + File.separator;
		ZipArchiveInputStream is = null;
		List<String> fileNames = new ArrayList<String>();

		try {
			is = new ZipArchiveInputStream(new BufferedInputStream(new FileInputStream(zipfile), BUFFER_SIZE));
			ZipArchiveEntry entry = null;
			while ((entry = is.getNextZipEntry()) != null) {
				fileNames.add(entry.getName());
				if (entry.isDirectory()) {
					File directory = new File(destDir, entry.getName());
					directory.mkdirs();
				} else {
					OutputStream os = null;
					try {
						os = new BufferedOutputStream(new FileOutputStream(new File(destDir, entry.getName())), BUFFER_SIZE);
						IOUtils.copy(is, os);
					} finally {
						IOUtils.closeQuietly(os);
					}
				}
			}
		} catch(Exception e) {
			e.printStackTrace();
			throw e;
		} finally {
			IOUtils.closeQuietly(is);
		}

		return fileNames;
	}

	public static List<String> unZip(String zipfile, String destDir) throws Exception {
		File zipFile = new File(zipfile);
		return unZip(zipFile, destDir);
	}

	/**
	 * 解压
	 * @param compressFile
	 * @param destDir
	 * @return
	 * @throws Exception
	 */
	public static List<String> unCompress(String compressFile, String destDir) throws Exception {
		String upperName= compressFile.toUpperCase();
		List<String> ret = null;
		if(upperName.endsWith(".ZIP")) {
			ret = unZip(compressFile, destDir);
		} else if(upperName.endsWith(".TAR")) {
			ret = unTar(compressFile, destDir);
		} else if(upperName.endsWith(".TAR.BZ2")) {
			ret = unTarBZip2(compressFile, destDir);
		} else if(upperName.endsWith(".BZ2")) {
			ret = unBZip2(compressFile, destDir);
		} else if(upperName.endsWith(".TAR.GZ")) {
			ret = unTarGZ(compressFile, destDir);
		} else if(upperName.endsWith(".GZ")) {
			ret = unGZ(compressFile, destDir);
		}
		return ret;
	}
}

  • 9
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

浮生若梦01

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值