FIle 文件操作,包括文件的复制、删除以及zip和rar格式的解压操作

由于rar压缩算法不公开,所以java api中没有rar的api,做使用rar之前必须使用开源jar包

< dependency >
     < groupId >com.github.junrar</ groupId >
     < artifactId >junrar</ artifactId >
     < version >0.7</ version >
</ dependency >

import java.io.BufferedInputStream;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipInputStream;

import com.github.junrar.Archive;
import com.github.junrar.exception.RarException;
import com.github.junrar.rarfile.FileHeader;

/**
 * 文件操作类
 * @author lintian
 * @since 2016-07-11
 */
public class FileOperateUtil {
    /**
     * 删除文件
     * @param basePath 文件路径
     */
    public static void deleteFiles(String basePath){
        File file=new File(basePath);
        deleteAllFiles(file);
        
    }
    /**
     * 删除所有文件
     * @param file
     */
    private static void deleteAllFiles(File file){
        if(file.exists()){
            if(file.isDirectory()){
                File[] tempFiles=file.listFiles();
                for(int i=0,len=tempFiles.length;i<len;i++){
                    if(tempFiles[i].isDirectory()){
                        deleteAllFiles(tempFiles[i]);
                        tempFiles[i].delete();
                    }else{
                        tempFiles[i].delete();
                    }
                }
            }else{
                file.delete();
            }
        }
    }
    /**
     * 从一个文件夹中复制所有文件数据到另一个文件夹中
     * @param fromPath
     * @param toPath
     * @throws IOException
     */
    public static void copyDirectiory(String fromPath,String toPath) throws IOException{
        deleteFiles(toPath);//复制到前段服务器之前先把服务器中的原始数据清空
        File fromFile=new File(fromPath);
        File toFile=new File(toPath);
        if(!toFile.exists()){//第一次判断是否存在站点根目录文件夹
            toFile.mkdir();
        }
        if(fromFile.exists()){
            if(fromFile.isDirectory()){
                File[] fromFileLists=fromFile.listFiles();
                for(int i=0,len=fromFileLists.length;i<len;i++){
                    if(fromFileLists[i].isDirectory()){
                        String orginPath=fromFileLists[i].getPath();
                        String targetPath=toFile.getPath()+File.separator+fromFileLists[i].getName();
                        copyDirectiory(orginPath, targetPath);
                    }else{
                        File targetFile=new File(toFile.getPath()+File.separator+fromFileLists[i].getName());
                        copyFile(fromFileLists[i],targetFile);
                    }
                }
            }
        }
    }
    
    /**
     * 复制文件
     * @param fromFile
     * @param toFile
     * @throws IOException
     */
    private static void copyFile(File fromFile,File toFile) throws IOException{
        BufferedInputStream bufferedInput=null;
        BufferedOutputStream bufferedOutput=null;
        FileInputStream fileInput=null;
        FileOutputStream fileOutput=null;
        fileInput=new FileInputStream(fromFile);
        fileOutput=new FileOutputStream(toFile);
        bufferedInput=new BufferedInputStream(fileInput);
        bufferedOutput=new BufferedOutputStream(fileOutput);
        byte data[]=new byte[1024];
        int count=0;
        while((count=fileInput.read(data,0,data.length))!=-1){
            fileOutput.write(data, 0,count);
        }
        bufferedOutput.flush();
        bufferedInput.close();
        bufferedOutput.close();
        fileOutput.close();
        fileInput.close();
        
    }
    /**
     * 解压文件
     * @param file
     * @throws IOException
     * @throws FileNotFoundException
     * @throws RarException
     */
    public static void deCompress(String filePath) throws FileNotFoundException, IOException, RarException{
        String ext=filePath.substring(filePath.lastIndexOf(".")+1, filePath.length());
        if("zip".equals(ext.trim())){
            zipDeCompress(filePath);
            deleteFiles(filePath);
        }else if("rar".equals(ext.trim())){
            rarDeCompress(filePath);
            deleteFiles(filePath);
        }else{
            throw new IOException("解压文件的格式不属于zip和rar");
        }
    
    }
    
    /**
     * 解压zip压缩文件,zip压缩文件中不能含有中文文件名
     * @param filePath
     * @throws ZipException
     * @throws IOException
     */
    private static void zipDeCompress(String filePath) throws ZipException, IOException{
        File file=new File(filePath);
        ZipEntry zEntry=null;
        ZipInputStream zipIn = new ZipInputStream(new FileInputStream(file));
        while((zEntry=zipIn.getNextEntry())!=null){
            if(zEntry.isDirectory()){
                String fileName=file.getPath().substring(0, file.getPath().lastIndexOf(File.separator))+File.separator+zEntry.getName();
                File fileDir=new File(fileName);
                if(!fileDir.exists()){
                    fileDir.mkdir();
                }
            }else{
                String    fileName=file.getPath().substring(0, file.getPath().lastIndexOf(File.separator))+File.separator+zEntry.getName();
                File targetFile=new File(fileName);
                FileOutputStream fout=new FileOutputStream(targetFile);
                byte data[]=new byte[1024];
                int count=0;
                while((count=zipIn.read(data,0,1024))!=-1){
                    fout.write(data, 0, count);
                }
                
                fout.flush();
                fout.close();
                
            }
        }
        zipIn.close();
    }
    /**
     * rar格式压缩文件解压
     * @param filePath
     * @throws RarException
     * @throws IOException
     */
    private static void rarDeCompress(String filePath) throws RarException, IOException {
        File file=new File(filePath);
        Archive archive = null;
        FileOutputStream unOut = null;
        archive = new Archive(file);
        FileHeader fileHeader ;
        while(( fileHeader = archive.nextFileHeader())!=null){
            if(fileHeader.isDirectory()){
                String fileName=file.getPath().substring(0, file.getPath().lastIndexOf(File.separator))+File.separator+fileHeader.getFileNameString();
                File fileDir=new File(fileName);
                if(!fileDir.exists()){
                    fileDir.mkdir();
                }
            }else{
                String    fileName=file.getPath().substring(0, file.getPath().lastIndexOf(File.separator))+File.separator+fileHeader.getFileNameString();
                File dir = new File(fileName.substring(0, fileName.lastIndexOf(File.separator)));
                if (!dir.exists() || !dir.isDirectory()) {
                    dir.mkdirs();
                }
                File targetFile=new File(fileName);
                unOut=new FileOutputStream(targetFile);
                archive.extractFile(fileHeader, unOut);
                unOut.flush();
                unOut.close();
            }
        }
        archive.close();
    }
    
}

程序测试可用,直接解压导入到工程就可以,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、付费专栏及课程。

余额充值