Java实现数据文件压缩和移动复制

Java实现数据文件压缩和移动复制

压缩:
package cn.com.sinosoft.tbf.common.util;

import java.io.*;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

import static org.springframework.util.StreamUtils.BUFFER_SIZE;

/**
 * 文件压缩工具
 *
 *
 */
public class ZipUtil {

	/**
	 * 压缩所有文件
	 * 
	 * @param files
	 * @param dest
	 * @throws Exception
	 */
	public static void zipAll(List<File> files, File dest) throws Exception {
		if(files == null || files.size() == 0 || dest == null) return;
		ZipOutputStream out = new ZipOutputStream(new FileOutputStream(dest));
		File zipParent = dest.getParentFile();
		if (!zipParent.exists()) {
			zipParent.mkdirs();
		}
		try {
			for (File file : files) {
				zip(out, file);
			}
		} finally {
			if (out != null) {
				out.close();
			}
		}
	}

	/**
	 * zip 压缩
	 * 
	 * @param source
	 *            源文件
	 * @param dest
	 *            目标文件
	 * @return
	 * @throws Exception
	 */
	public static void zip(File source, File dest) throws Exception {
		ZipOutputStream out = null;
		try {
			File zipParent = dest.getParentFile();
			if (!zipParent.exists()) {
				zipParent.mkdirs();
			}
			out = new ZipOutputStream(new FileOutputStream(dest));
			zip(out, source);
		} finally {
			if (out != null) {
				out.close();
				// 删除源文件
				// source.delete();
			}
		}
	}

	public static void zip(ZipOutputStream out, File f) throws Exception {
		if (f == null || !f.exists() || !f.isFile())
			return;
		out.putNextEntry(new ZipEntry(f.getName()));
		FileInputStream in = new FileInputStream(f);
		BufferedInputStream bi = new BufferedInputStream(in);
		int b;
		byte[] buffer = new byte[512];
		try {
			while ((b = bi.read(buffer)) != -1) {
				out.write(buffer, 0, b);
			}
		} finally {
			bi.close();
			in.close();
		}
	}


	/**
	 * zip解压
	 * @param srcFile        zip源文件
	 * @param destDirPath     解压后的目标文件夹
	 * @throws RuntimeException 解压失败会抛出运行时异常
	 */
	public static void unZip(File srcFile, String destDirPath) throws RuntimeException {
		long start = System.currentTimeMillis();
		// 判断源文件是否存在
		if (!srcFile.exists()) {
			throw new RuntimeException(srcFile.getPath() + "所指文件不存在");
		}
		// 开始解压
		ZipFile zipFile = null;
		try {
			zipFile = new ZipFile(srcFile);
			Enumeration<?> entries = zipFile.entries();
			while (entries.hasMoreElements()) {
				ZipEntry entry = (ZipEntry) entries.nextElement();
				System.out.println("解压文件:" + entry.getName());
				// 如果是文件夹,就创建个文件夹
				if (entry.isDirectory()) {
					String dirPath = destDirPath + "/" + entry.getName();
					File dir = new File(dirPath);
					dir.mkdirs();
				} else {
					// 如果是文件,就先创建一个文件,然后用io流把内容copy过去
					File file = new File(destDirPath + "/" + entry.getName());
					// 保证这个文件的父文件夹必须要存在
					if(!file.getParentFile().exists()){
						file.getParentFile().mkdirs();
					}
					file.createNewFile();
					// 将压缩文件内容写入到这个文件中
					InputStream is = zipFile.getInputStream(entry);
					FileOutputStream fos = new FileOutputStream(file);
					int len;
					byte[] buf = new byte[BUFFER_SIZE];
					while ((len = is.read(buf)) != -1) {
						fos.write(buf, 0, len);
					}
					// 关流顺序,先打开的后关闭
					fos.close();
					is.close();
				}
			}
			long end = System.currentTimeMillis();
			System.out.println("解压完成,耗时:" + (end - start) +" ms");
		} catch (Exception e) {
			throw new RuntimeException("unzip error from ZipUtils", e);
		} finally {
			if(zipFile != null){
				try {
					zipFile.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

}

复制和移动
package cn.com.sinosoft.tbf.common.util;

import org.apache.commons.io.FileUtils;

import java.io.*;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 文件操作
 */
public class FileUtil {

    public static void main(String[] args) throws IOException {
        // copyFile("C:\\temp\\ehr_data_files\\src\\EHR_CHILD_DIS_SCREENDIAG\\418035665\\EHR_CHILD_DIS_SCREENDIAG-418035665-20190309.json.zip","C:\\temp\\ehr_data_files\\send\\haha.zip");
//        deleteFile("E:\\test\\upload\\");

        File fileFrom = new File("C:\\temp\\ehr_data_files\\src\\EHR_CHILD_DIS_SCREENDIAG\\418035665\\EHR_CHILD_DIS_SCREENDIAG-418035665-20190309.json.zip");
        File fileTo = new File("C:\\temp\\ehr_data_files\\send\\hehe.zip");
        copyFileUsingApacheCommonsIO(fileFrom,fileTo);
    }    /**
     * 移动 文件或者文件夹
     * @param oldPath
     * @param newPath
     * @throws IOException
     */
    public static void moveTo(String oldPath,String newPath) throws IOException {
        copyFile(oldPath,newPath);
        deleteFile(oldPath);
    }

    /**
     * 删除 文件或者文件夹
     * @param filePath
     */
    public static void deleteFile(String filePath){
        File file = new File(filePath);
        if (!file.exists()) {
            return;
        }
        if (file.isDirectory() ) {
            File[] list = file.listFiles();

            for (File f : list) {
                deleteFile(f.getAbsolutePath()) ;
            }
        }
        file.delete();
    }

    /**
     * 复制 文件或者文件夹
     * @param oldPath
     * @param newPath
     * @throws IOException
     */
    public static void  copyFile(String oldPath ,String newPath ) throws IOException {
        System.out.println("copy file from [" + oldPath + "] to [" + newPath +"]");

        File oldFile = new File(oldPath) ;
        if  (oldFile.exists())  {

            if(oldFile.isDirectory()){ // 如果是文件夹
                File newPathDir = new File(newPath);
                newPathDir.mkdirs();
                File[] lists = oldFile.listFiles() ;
                if(lists != null && lists.length > 0 ){
                    for (File file : lists) {
                        copyFile(file.getAbsolutePath(), newPath.endsWith(File.separator) ? newPath + file.getName() : newPath + File.separator + file.getName()) ;
                    }
                }
            }else {
                InputStream  inStream  =  new  FileInputStream(oldFile);  //读入原文件
                FileOutputStream  fs  =  new  FileOutputStream(newPath);
                write2Out(inStream ,fs) ;
                inStream.close();
            }
        }
    }

    /**
     * 重命名文件
     * @param file
     * @param name
     * @return
     */
    public static File renameFile(File file , String name ){
        String fileName = file.getParent()  + File.separator + name ;
        File dest = new File(fileName);
        file.renameTo(dest) ;
        return dest ;
    }

    /**
     * 压缩多个文件。
     * @param zipFileName 压缩输出文件名
     * @param files 需要压缩的文件
     * @return
     * @throws Exception
     */
    public static File createZip(String zipFileName, File... files) throws Exception {
        File outFile = new File(zipFileName) ;
        ZipOutputStream out = null;
        BufferedOutputStream bo = null;
        try {
            out = new ZipOutputStream(new FileOutputStream(outFile));
            bo = new BufferedOutputStream(out);

            for (File file : files) {
                zip(out, file, file.getName(), bo);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                bo.close();
            } finally {
                out.close(); // 输出流关闭
            }
        }
        return outFile;
    }

    /**
     *
     * @param zipFileName 压缩输出文件名
     * @param inputFile 需要压缩的文件
     * @return
     * @throws Exception
     */
    public static File createZip(String zipFileName, File inputFile) throws Exception {
        File outFile = new File(zipFileName) ;
        ZipOutputStream out = null;
        BufferedOutputStream bo = null;
        try {
            out = new ZipOutputStream(new FileOutputStream(outFile));
            bo = new BufferedOutputStream(out);
            zip(out, inputFile, inputFile.getName(), bo);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                bo.close();
            } finally {
                out.close(); // 输出流关闭
            }
        }
        return outFile;
    }

    private static void zip(ZipOutputStream out, File f, String base,BufferedOutputStream bo) throws Exception { // 方法重载
        if (f.isDirectory()) {
            File[] fl = f.listFiles();
            if ( fl == null ||  fl.length == 0) {
                out.putNextEntry(new ZipEntry(base + "/")); // 创建创建一个空的文件夹
            }else{
                for (int i = 0; i < fl.length; i++) {
                    zip(out, fl[i], base + "/" + fl[i].getName(), bo); // 递归遍历子文件夹
                }
            }

        } else {
            out.putNextEntry(new ZipEntry(base)); // 创建zip压缩进入 base 文件
            System.out.println(base);
            BufferedInputStream bi = new BufferedInputStream(new FileInputStream(f));

            try {
                write2Out(bi,out) ;
            } catch (IOException e) {
                //Ignore
            }finally {
                bi.close();// 输入流关闭
            }
        }
    }

    private static void write2Out(InputStream input , OutputStream out) throws IOException {
        byte[] b = new byte[1024];
        int c = 0 ;
        while ( (c = input.read(b)) != -1 ) {
            out.write(b,0,c);
            out.flush();
        }
        out.flush();
    }

    /**
     * 使用FileUtils拷贝文件
     * @param source
     * @param dest
     * @throws IOException
     */
    public static void copyFileUsingApacheCommonsIO(File source, File dest)
            throws IOException {
        FileUtils.copyFile(source, dest);
    }
}


程序测试可用,直接解压导入到工程就可以,bat文件跟shell文件是用于在window跟linux上直接执行的脚本 我把开发的配置文档附上: 1.程序为定时任务,任务执行时间在bin目录下的配置文件mergeFilleUtil.properties中配置,在配置文件中,TASK_PERIOD表示任务执行时间间隔,单位为妙,如一天的时间间隔配置是86400,TASK_BEGIN_HOUR表示任务开始的小时时间,比如9点,TASK_BEGIN_MINUTE表任务开始的分钟,比如30分。 2. 程序用log4j记录日志,日志分正常信息跟错误信息两个级别,日志文件存放在log4j文件夹下。考虑到文件很多,日志解压、移动文件每解压、移动1000个记录一次,合、删除文件每合、删除50000个记录一次, 3. 启动任务前需配置文件解压合的路径,本程序需配置的路径如下: 1). PROVINCE_DIR:原始文件存放的路径,必须配置到省的上一级路径,比如存放安徽省的文件路径为E:\test\rootfile\anhui,那么文件的路径必须配置为E:\test\rootfile,否则不能正确显示合结果; 2). UN_ZIP_PATH:存放解压后的文件的路径; 3). OUT_PATH:存放合后的文件路径; 4). DONE_FILE_PATH:存放已经解压处理过的文件; 5). DELETE_PATH:配置程序运行结束后欲删除文件的路径,如想删除多个文件夹下的文件,路径之间用逗号隔开,勿加空格,比如:E:\test\rootfile,E:\test\unZip; 4. 注意事项: 本解压合程序处理文件的逻辑如下: 程序每次解压都去PROVINCE_DIR文件下去解压,将解压后的文件存放到UN_ZIP_PATH下,之后程序启动合程序合UN_ZIP_PATH下文件,将合后的文件按照省份名称存放到OUT_PATH,一个一个文件。当解压合结束后,程序将PROVINCE_DIR路径下的文件移动到DONE_FILE_PATH下,且删除PROVINCE_DIR跟UN_ZIP_PATH下文件,这样保证程序每次运行PROVINCE_DIR文件夹下的文件跟UN_ZIP_PATH下的文件都是最新未处理过的,避免了不断判断文件历史记录所带来的大量时间消耗。 所以为了保证文件解压跟合的正确性,必须配置好DELETE_PATH路径下的文件,否则合后的结果是不准确的。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值