文件操作工具类

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;

/**
 * 文件操作工具类
 * 
 * @author shi 2020年5月12日14:10:52
 */
public class FileUtil {
    // 开始复制
    public static void copy(String src, String newpath) {
        File file = new File(src);
        if (file.isFile()) {
            fileCopy(file.getPath(), newpath + "/" + file.getName());
        } else if (file.isDirectory()) {
            File[] fs = file.listFiles();
            // 创建文件夹
            File file2 = new File(newpath);
            if (!file2.exists()) {
                file2.mkdirs();
            }
            if (fs != null) {
                for (File f : fs) {
                    if (f.isFile()) {
                        fileCopy(f.getPath(), newpath + "/" + f.getName()); // 调用文件拷贝的方法
                    } else if (f.isDirectory()) {
                        copy(f.getPath(), newpath + "/" + f.getName());
                    }
                }
            }
        } else {
            System.out.println("文件异常");
        }
    }

    // 复制文件
    public static void fileCopy(String src, String newpath) {
        FileOutputStream fos = null;
        FileInputStream fis = null;
        try {
            fos = new FileOutputStream(newpath);
            fis = new FileInputStream(src);
            byte[] buf = new byte[2048];
            int len = 0;
            while ((len = fis.read(buf)) != -1) {
                fos.write(buf, 0, len);
            }
            fos.flush();
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("复制失败");
        } finally {
            try {
                if (fis != null)
                    fis.close();
                fos.close();
            } catch (IOException e) {
                throw new RuntimeException("读取失败");
            }
        }
    }

    // 删除所有文件及文件夹
    public static boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            for (int i = 0; i < children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        // 目录此时为空,可以删除
        return dir.delete();
    }
    
    // 解压文件
    public static Map<String,String> decompress(File uploadfile) {
        ZipFile zf = null;
        InputStream is = null;
        FileOutputStream fos = null;
        String assemblyName = uploadfile.getName().substring(0, uploadfile.getName().lastIndexOf("."));
        int index;
        String osName = System.getProperty("os.name");
        if(osName.indexOf("Windows")>=0) {
            index = uploadfile.getAbsolutePath().lastIndexOf("\");
        }else {
            index = uploadfile.getAbsolutePath().lastIndexOf("/");
        }
        Map<String,String> returnMap=new HashMap<String,String>();
        boolean frist = true;
        try {
            zf = new ZipFile(uploadfile);
            Enumeration entries = zf.getEntries();
            ZipEntry entry = null;
            while (entries.hasMoreElements()) {
                entry = (ZipEntry) entries.nextElement();
                System.out.println("正在解压文件---->" + entry.getName());
                if (entry.isDirectory()) {
                } else {
                    File f =null;
                    if(entry.getName().indexOf("images/thumbnail/")>=0) {
                        String imgtype = entry.getName().substring(entry.getName().lastIndexOf("."),entry.getName().length());
                         f = new File(uploadfile.getAbsolutePath().substring(0,index+1) +assemblyName+ "/images/thumbnail/"+assemblyName+imgtype);
                    }else if(entry.getName().indexOf("/options")>=0){
                         f = new File(uploadfile.getAbsolutePath().substring(0,index+1) +assemblyName+"/options/"+assemblyName+".json");
                    }else {
                         f = new File(uploadfile.getAbsolutePath().substring(0,index+1) + entry.getName());
                    }
                    if (!f.exists()) {
                        File dirs = f.getParentFile();
                        dirs.mkdirs();
                    }
                    f.createNewFile();
                    is = zf.getInputStream(entry);
                    fos = new FileOutputStream(f);
                    //临时处理
                    if(entry.getName().indexOf("images/thumbnail/")>=0) {
                        returnMap.put("img", entry.getName().substring(entry.getName().lastIndexOf("/")+1, entry.getName().length()));
                    }
                    if(entry.getName().indexOf("/options")>=0) {
                        returnMap.put("option", entry.getName().substring(entry.getName().lastIndexOf("/")+1, entry.getName().length()));
                    }
                    // 将压缩文件内容写入到这个文件中
                    try {
                        int count;
                        byte[] buf = new byte[8192];
                        while ((count = is.read(buf)) != -1) {
                            fos.write(buf, 0, count);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            if (is != null)
                                is.close();
                            fos.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } finally {
            try {
                if (is != null)
                    is.close();
                fos.close();
                zf.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return returnMap;
    }
    
    /**
    * 把一个文件转化为byte字节数组。
    *
    * @return
    */
    public static byte[] fileConvertToByteArray(File file) {
        byte[] data = null;

        try {
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            int len;
            byte[] buffer = new byte[1024];
            while ((len = fis.read(buffer)) != -1) {
                baos.write(buffer, 0, len);
            }

            data = baos.toByteArray();

            fis.close();
            baos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return data;
    }
}
原文地址:https://www.cnblogs.com/sunliyuan/p/13516084.html