zoukankan      html  css  js  c++  java
  • 文件操作工具类与压缩文件工具类:上传文件、读取文件和压缩文件等

    package com.shd.biz.dataManagement.util;
    
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.OutputStream;
    import java.nio.file.Files;
    import java.nio.file.LinkOption;
    import java.nio.file.Path;
    import java.nio.file.Paths;
    import java.nio.file.attribute.BasicFileAttributeView;
    import java.nio.file.attribute.BasicFileAttributes;
    import java.util.ArrayList;
    import java.util.Date;
    import java.util.List;
    
    import org.springframework.web.multipart.MultipartFile;
    
    import com.shd.core.basebiz.dto.DataRecord;
    
    
    
    /**
     * 
     * @function 文件操作工具类
     * @author Liangjw
     * @date 2019-5-9 上午11:10:57
     * @version    
     * @since JDK 1.7
     */
    public class FileUtil {
        
        /**
         * 
         * @function 删除文件.
         * @author Liangjw  
         * @date 2019-5-9 上午10:27:32  
         * @param file 文件
         * @return
         */
        public static boolean deleteFile(File file){
            boolean msg = true;
            if(file.exists()){
                if(file.isDirectory()){
                    File[] files = file.listFiles();
                    if(files != null && files.length > 0){
                        for(File temp : files){
                            msg = deleteFile(temp);
                            if(!msg){
                                return msg;
                            }
                        }
                    }
                    msg = file.delete();
                }else{
                    msg = file.delete();
                }
            }
            return msg;
        }
        
        /**
         * 
         * @function 保存文件到指定目录.
         * @author Liangjw  
         * @date 2019-5-9 上午10:03:45  
         * @param file 文件
         * @param savePath 上传路径
         * @return
         * @throws Exception
         */
        public static String saveUploadFile(MultipartFile file, String savePath) throws Exception{
            File fileDir = new File(savePath);
            if(!fileDir.exists()){
                fileDir.mkdirs();
            }
            
            String filePath = "";
            String fileName = file.getOriginalFilename();
            fileName = fileName.replaceAll(" ","");            
            filePath = savePath + File.separator + fileName;
                
            InputStream ins = file.getInputStream();
            OutputStream orious = new FileOutputStream(filePath);
            try {
                byte[] buffer = new byte[4096];
                int len = 0;
                while ((len = ins.read(buffer)) > -1) {
                    orious.write(buffer, 0, len);
                }
            }finally {
                orious.flush();
                orious.close();
                ins.close();
            }
            return filePath;
        }
        
        /**
         * 
         * @function 保存文件到指定目录,并以新名称命名.
         * @author Liangjw  
         * @date 2019-5-23 上午11:30:43  
         * @param file 文件
         * @param savePath 保存目录
         * @param newFileName 新名称
         * @return
         * @throws Exception
         */
        public static String saveUploadFile(MultipartFile file, String savePath, String newFileName) throws Exception{
            File fileDir = new File(savePath);
            if(!fileDir.exists()){
                fileDir.mkdirs();
            }
            
            String filePath = savePath + File.separator + newFileName;
            File oldFile = new File(filePath);
            if(oldFile.exists()){
                oldFile.delete();
            }
            InputStream ins = file.getInputStream();
            OutputStream orious = new FileOutputStream(filePath);
            try {
                byte[] buffer = new byte[4096];
                int len = 0;
                while ((len = ins.read(buffer)) > -1) {
                    orious.write(buffer, 0, len);
                }
            }finally {
                orious.flush();
                orious.close();
                ins.close();
            }
            return filePath;
        }
        
        /**
         * 
         * @function 复制文件内容到新的文件.
         * @author Liangjw  
         * @date 2019-5-15 上午10:23:39  
         * @param oldFile 旧文件
         * @param newFilePath 新文件路径
         * @return
         * @throws Exception
         */
        public static String copyFile(File oldFile, String newFilePath) throws Exception{
            File tempFile = new File(newFilePath);
            if(!tempFile.getParentFile().exists()){
                tempFile.getParentFile().mkdirs();
            }
            if(!tempFile.exists()){
                tempFile.createNewFile();
            }
            
            InputStream ins = new FileInputStream(oldFile);
            OutputStream orious = new FileOutputStream(tempFile);
            try {
                byte[] buffer = new byte[4096];
                int len = 0;
                while ((len = ins.read(buffer)) > -1) {
                    orious.write(buffer, 0, len);
                }
                return "成功";
            } catch(Exception e){
                return "失败";
            } finally {
                orious.flush();
                orious.close();
                ins.close();
            }
        }
        
        /**
         * 
         * @function 返回某个路径下所有文件(包括子目录下的所有文件).
         * @author Liangjw  
         * @date 2019-5-10 下午02:47:01  
         * @param path 访问路径
         * @return
         * @throws Exception
         */
        public static List<File> getFilesByPath(String path) throws Exception{
            List<File> result = new ArrayList<File>();
            File resultFile = new File(path);
            if(resultFile.isDirectory()){
                File[] files = resultFile.listFiles();
                for(File file : files){
                    if(file.isDirectory()){
                        result.addAll(getFilesByPath(file.getAbsolutePath()));
                    }else{
                        result.add(file);
                    }
                }
            }else{
                result.add(resultFile);
            }
            return result;
        }
        
        /**
         * 
         * @function 返回某个路径下所有文件的路径(包括子目录下的所有文件).
         * @author Liangjw  
         * @date 2019-5-24 上午11:24:48  
         * @param path 访问路径
         * @return
         * @throws Exception
         */
        public static List<String> getFilePathsByPath(String path) throws Exception{
            List<String> result = new ArrayList<String>();
            File resultFile = new File(path);
            if(resultFile.isDirectory()){
                File[] files = resultFile.listFiles();
                for(File file : files){
                    if(file.isDirectory()){
                        result.addAll(getFilePathsByPath(file.getAbsolutePath()));
                    }else{
                        result.add(file.getAbsolutePath());
                    }
                }
            }else{
                result.add(resultFile.getAbsolutePath());
            }
            return result;
        }
        
        /**
         * 
         * @function 获取该路径下一个合适的文件名(当创建文件出现同名时使用,返回一个唯一名称).
         * @author Liangjw  
         * @date 2019-5-24 下午04:55:34  
         * @param path 文件保存路径
         * @param fileName 文件名
         * @return
         */
        public static String getSuitableFileName(String path, String fileName){
            if(new File(path + File.separator + fileName).exists()){
                int i = 1;
                String pre = fileName.substring(0, fileName.indexOf("."));
                String next = fileName.substring(fileName.indexOf("."), fileName.length());
                while(new File(path + File.separator + pre + "_" + i + next).exists()){
                    i++;
                }
                return pre + "_" + i + next;
            }else{
                return fileName;
            }
        }
        
        /**
         * 
         * @function 解析txt文件,返回航点列表.
         * @author Liangjw  
         * @date 2019-5-13 下午02:21:42  
         * @param file txt文件
         * @return
         * @throws Exception
         */
        public static List<DataRecord> resolveTxt(File file) throws Exception{
            List<DataRecord> result = new ArrayList<DataRecord>();
            
            if(file.exists()){
                FileInputStream fin = new FileInputStream(file);
                InputStreamReader in = new InputStreamReader(fin);
                BufferedReader br = new BufferedReader(in);
                try {
                    String line;
                    int index = 0;
                    DataRecord temp = null;
                    while ((line = br.readLine()) != null) {
                        if(line.trim().equals("")){
                            index++;
                            continue;
                        }
    /*                    if(index == 0){
                            index++;
                            continue;
                        }
    */                    
                        String[] arr = line.split("\s+");
                        temp = new DataRecord();
                        temp.put("TASK_ID", arr[0]);
                        temp.put("POINT_ID", arr[1]);
                        temp.put("TIME", arr[2]);
                        if(arr.length > 3){
                            if(arr[3].indexOf(',') != -1){
                                String[] actions = arr[3].split(",");
                                for (String string : actions) {
                                    if(string.indexOf('$') != -1){
                                        string = string.substring(0, string.indexOf("$"));
                                    }
                                    temp.put("POINT_ACTION_CODE", string);
                                    result.add(temp);
                                }
                            }else{
                                if(arr[3].indexOf('$') != -1){
                                    arr[3] = arr[3].substring(0, arr[3].indexOf("$"));
                                }
                                temp.put("POINT_ACTION_CODE", arr[3]);
                                result.add(temp);
                            }
                        }else{
                            result.add(temp);
                        }
                        index++;
                    }
                } catch (Exception e) {
                    // TODO: handle exception
                } finally {
                    br.close();
                    in.close();
                    fin.close();
                }
            }
            
            return result;
        }
        
        /**
         * 
         * @function 获取文件的创建时间.
         * @author Liangjw  
         * @date 2019-5-27 下午01:40:34  
         * @param file 文件
         * @return
         */
        public static Date getFileCreateTime(File file){
            Path path = Paths.get(file.getAbsolutePath());
            BasicFileAttributeView basicview = Files.getFileAttributeView(path, BasicFileAttributeView.class,
                    LinkOption.NOFOLLOW_LINKS);
            BasicFileAttributes attr;
            try {
                attr = basicview.readAttributes();
                return new Date(attr.creationTime().toMillis());
            } catch (Exception e) {
                return null;
            }
        }
        
        /**
         * 
         * @function 判断文件格式是否符合要求.
         * 符合要求格式有:JPG、PNG、AVI、MOV、RMVB、FLV、MP4、MP3
         * @author Liangjw  
         * @date 2019-7-9 上午11:44:34  
         * @param fileName 文件名
         * @return
         */
        public static boolean ifFileFormat(String fileName){
            if(fileName.indexOf(".JPG") != -1 || fileName.indexOf(".jpg") != -1 ||
                    fileName.indexOf(".PNG") != -1 || fileName.indexOf(".png") != -1 ||
                    fileName.indexOf(".AVI") != -1 || fileName.indexOf(".avi") != -1 ||
                    fileName.indexOf(".MOV") != -1 || fileName.indexOf(".mov") != -1 ||
                    fileName.indexOf(".RMVB") != -1 || fileName.indexOf(".rmvb") != -1 ||
                    fileName.indexOf(".FLV") != -1 || fileName.indexOf(".flv") != -1 ||
                    fileName.indexOf(".MP4") != -1 || fileName.indexOf(".mp4") != -1 ||
                    fileName.indexOf(".MP3") != -1 || fileName.indexOf(".mp3") != -1){
                return true;
            }
            return false;
        }
        
        /**
         * 
         * @function 判断文件是否为图片.
         * @author Liangjw  
         * @date 2019-7-11 下午02:57:06  
         * @param fileName 文件名
         * @return
         */
        public static boolean ifFileAsImg(String fileName){
            if(fileName.indexOf(".JPG") != -1 || fileName.indexOf(".jpg") != -1 ||
                    fileName.indexOf(".PNG") != -1 || fileName.indexOf(".png") != -1){
                return true;
            }
            return false;
        }
        
    }
    package com.shd.biz.dataManagement.util;
    
    import java.io.File;
    
    /**
     * 
     * @function 压缩工具类
     * @author Liangjw
     * @date 2019-5-15 上午11:01:30
     * @version    
     * @since JDK 1.7
     */
    public class ZipUtils {
    
        private static final int BUFFER_SIZE = 2 * 1024;
        
        public static void toZip(String srcDir, OutputStream out, boolean KeepDirStructure)throws RuntimeException{
            long start = System.currentTimeMillis();
            ZipOutputStream zos = null ;
            try {
                zos = new ZipOutputStream(out);
                zos.setEncoding("gbk");
                File sourceFile = new File(srcDir);
                compress(sourceFile,zos,sourceFile.getName(),KeepDirStructure);
                long end = System.currentTimeMillis();
                System.out.println("压缩完成,耗时:" + (end - start) +" ms");
            } catch (Exception e) {
                throw new RuntimeException("zip error from ZipUtils",e);
            }finally{
                if(zos != null){
                    try {
                        zos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            
        }
        
        /**
         * 压缩成ZIP 方法2
         * @param srcFiles 需要压缩的文件列表
         * @param out           压缩文件输出流
         * @throws RuntimeException 压缩失败会抛出运行时异常
         */
        public static void toZip(List<File> srcFiles , OutputStream out)throws RuntimeException {
            long start = System.currentTimeMillis();
            ZipOutputStream zos = null ;
            try {
                zos = new ZipOutputStream(out);
                for (File srcFile : srcFiles) {
                    byte[] buf = new byte[BUFFER_SIZE];
                    zos.putNextEntry(new ZipEntry(srcFile.getName()));
                    int len;
                    FileInputStream in = new FileInputStream(srcFile);
                    while ((len = in.read(buf)) != -1){
                        zos.write(buf, 0, len);
                    }
                    zos.closeEntry();
                    in.close();
                }
                long end = System.currentTimeMillis();
                System.out.println("压缩完成,耗时:" + (end - start) +" ms");
            } catch (Exception e) {
                throw new RuntimeException("zip error from ZipUtils",e);
            }finally{
                if(zos != null){
                    try {
                        zos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        /**
         * 递归压缩方法
         * @param sourceFile 源文件
         * @param zos        zip输出流
         * @param name       压缩后的名称
         * @param KeepDirStructure  是否保留原来的目录结构,true:保留目录结构; 
         *                          false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
         * @throws Exception
         */
        private static void compress(File sourceFile, ZipOutputStream zos, String name,
                boolean KeepDirStructure) throws Exception{
            byte[] buf = new byte[BUFFER_SIZE];
            if(sourceFile.isFile()){
                // 向zip输出流中添加一个zip实体,构造器中name为zip实体的文件的名字
                zos.putNextEntry(new ZipEntry(name));
                
                //zos.putNextEntry(new ZipEntry(name));
                System.out.println(name);
                // copy文件到zip输出流中
                int len;
                FileInputStream in = new FileInputStream(sourceFile);
                //BufferedReader in=new BufferedReader(new InputStreamReader(fileInputStream,"GBK"));
                while ((len = in.read(buf)) != -1){
                    zos.write(buf, 0, len);
                }
                
                // Complete the entry
                zos.closeEntry();
                in.close();
            } else {
                File[] listFiles = sourceFile.listFiles();
                if(listFiles == null || listFiles.length == 0){
                    // 需要保留原来的文件结构时,需要对空文件夹进行处理
                    if(KeepDirStructure){
                        // 空文件夹的处理
                        zos.putNextEntry(new ZipEntry(name + "/"));
                        // 没有文件,不需要文件的copy
                        zos.closeEntry();
                    }
                }else {
                    for (File file : listFiles) {
                        // 判断是否需要保留原来的文件结构
                        if (KeepDirStructure) {
                            // 注意:file.getName()前面需要带上父文件夹的名字加一斜杠,
                            // 不然最后压缩包中就不能保留原来的文件结构,即:所有文件都跑到压缩包根目录下了
                            compress(file, zos, name + "/" + file.getName(),KeepDirStructure);
                        } else {
                            compress(file, zos, file.getName(),KeepDirStructure);
                        }
                        
                    }
                }
            }
        }
    }
  • 相关阅读:
    CKEDITOR最新版不能上传图片的解决
    Java Web开发之Servlet获取ckeditor内容
    『实践』Java Web开发之分页(ajax)
    Java开发之JSP行为
    [Wpf学习] 1.传说中的Main
    直接使用汇编编写 .NET Standard 库
    ASP.NET CORE 启动过程及源码解读
    使用EventBus + Redis发布订阅模式提升业务执行性能(下)
    Android 实现浏览器跳转APP应用,网页也可以跳转APP
    Python全栈(七)Flask框架之1.Flask简介与URL和视图介绍
  • 原文地址:https://www.cnblogs.com/4AMLJW/p/fileTools202005180942.html
Copyright © 2011-2022 走看看