Java批量下载并打成压缩包zip格式

    @ApiOperation("批量下载并打成压缩包zip格式")
    @Log(title = "批量下载并打成压缩包zip格式", businessType = BusinessType.OTHER)
    @PostMapping("/common/downloadZipFiles")
    @ResponseBody
    public void downloadFiles(HttpServletRequest request, HttpServletResponse response,@RequestBody JSONObject jsonParam)  throws Exception {
        ArrayList<Object> pathArray=(ArrayList)jsonParam.get("remoteDirectoryPath");

        // 设置文件后缀
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String fn = "myData_" + sdf.format(new Date());
        // 读取字符编码
        String utf = "UTF-8";

        // 设置响应
        response.setContentType("application/ms-txt.numberformat:@");
        response.setCharacterEncoding(utf);
        response.setHeader("Pragma", "public");
        response.setHeader("Cache-Control", "max-age=30");
        //response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fn, utf));
        response.setHeader("Content-Disposition",
                "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, fn+".zip"));//重新生成的新文件的名字

        // 设置压缩流:直接写入response,实现边压缩边下载
        ZipOutputStream zipos = null;
        try {
            zipos = new ZipOutputStream(new BufferedOutputStream(response.getOutputStream()));
            zipos.setMethod(ZipOutputStream.DEFLATED); // 设置压缩方法
        } catch (Exception e) {
            e.printStackTrace();
        }

        //把将要下载的文件 都统一放在同一个临时文件夹下面
        String filePath = geneConfig.getFileUploadPath()+fn;

        for (Object pathObj:pathArray){
            HashMap jsonObject=(HashMap)pathObj;

            Integer type=(Integer)jsonObject.get("type");
            String path=(String)jsonObject.get("path");

            if (0==type){//文件夹
                File file = new File(path);
                CreateFileUtil.copyFolder(path,filePath+File.separator+file.getName());//复制整个文件夹内容
            }else {
                File file = new File(path);
                CreateFileUtil.copyFile(path,filePath+File.separator+file.getName());//复制单个文件
            }
        }

        //将合并后的文件夹下载
        File sourceFile = new File(filePath);
        ZipUtils.compress(sourceFile,zipos,sourceFile.getName(),true);

        // 关闭流
        try {
            zipos.closeEntry();
            zipos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //删除临时文件夹
        //FileHandleUtil.deleteFolder(filePath);
    }
package com.hessianhealth.common.utils.file;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.URLEncoder;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

/**
 * 文件处理工具类
 * 
 * @author lgn
 */
public class FileUtils extends org.apache.commons.io.FileUtils
{
    public static String FILENAME_PATTERN = "[a-zA-Z0-9_\\-\\|\\.\\u4e00-\\u9fa5]+";

    /**
     * 输出指定文件的byte数组
     * 
     * @param filePath 文件路径
     * @param os 输出流
     * @return
     */
    public static void writeBytes(String filePath, OutputStream os) throws IOException
    {
        FileInputStream fis = null;
        try
        {
            File file = new File(filePath);
            if (!file.exists())
            {
                throw new FileNotFoundException(filePath);
            }
            fis = new FileInputStream(file);
            byte[] b = new byte[1024];
            int length;
            while ((length = fis.read(b)) > 0)
            {
                os.write(b, 0, length);
            }
        }
        catch (IOException e)
        {
            throw e;
        }
        finally
        {
            if (os != null)
            {
                try
                {
                    os.close();
                }
                catch (IOException e1)
                {
                    e1.printStackTrace();
                }
            }
            if (fis != null)
            {
                try
                {
                    fis.close();
                }
                catch (IOException e1)
                {
                    e1.printStackTrace();
                }
            }
        }
    }

    /**
     * 删除文件
     * 
     * @param filePath 文件
     * @return
     */
    public static boolean deleteFile(String filePath)
    {
        boolean flag = false;
        File file = new File(filePath);
        // 路径为文件且不为空则进行删除
        if (file.isFile() && file.exists())
        {
            file.delete();
            flag = true;
        }
        return flag;
    }

    /**
     * 文件名称验证
     * 
     * @param filename 文件名称
     * @return true 正常 false 非法
     */
    public static boolean isValidFilename(String filename)
    {
        return filename.matches(FILENAME_PATTERN);
    }

    /**
     * 下载文件名重新编码
     * 
     * @param request 请求对象
     * @param fileName 文件名
     * @return 编码后的文件名
     */
    public static String setFileDownloadHeader(HttpServletRequest request, String fileName)
            throws UnsupportedEncodingException
    {
        final String agent = request.getHeader("USER-AGENT");
        String filename = fileName;
        if (agent.contains("MSIE"))
        {
            // IE浏览器
            filename = URLEncoder.encode(filename, "utf-8");
            filename = filename.replace("+", " ");
        }
        else if (agent.contains("Firefox"))
        {
            // 火狐浏览器
            filename = new String(fileName.getBytes(), "ISO8859-1");
        }
        else if (agent.contains("Chrome"))
        {
            // google浏览器
            filename = URLEncoder.encode(filename, "UTF-8");
            //filename=new String(filename.getBytes("UTF-8"),"UTF-8");
        }
        else
        {
            // 其它浏览器
            // 万能乱码问题解决
            filename = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
        }
        return filename;
    }



    /**
     * 将一段错误解码的字符串重新解码
     */
    public static String convertEncodingFormat(String str, String formatFrom, String FormatTo) {
        String result = null;
        if (!(str == null || str.length() == 0)) {
            try {
                result = new String(str.getBytes(formatFrom), FormatTo);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 获取编码格式
     * @param str
     * @return
     */
    public static String getEncoding(String str) {
        String encode = "GB2312";
        try {
            if (str.equals(new String(str.getBytes(encode), encode))) { //判断是不是GB2312
                String s = encode;
                return s; //是的话,返回“GB2312“,以下代码同理
            }
        } catch (Exception exception) {
        }
        encode = "ISO-8859-1";
        try {
            if (str.equals(new String(str.getBytes(encode), encode))) { //判断是不是ISO-8859-1
                String s1 = encode;
                return s1;
            }
        } catch (Exception exception1) {
        }
        encode = "UTF-8";
        try {
            if (str.equals(new String(str.getBytes(encode), encode))) { //判断是不是UTF-8
                String s2 = encode;
                return s2;
            }
        } catch (Exception exception2) {
        }
        encode = "GBK";
        try {
            if (str.equals(new String(str.getBytes(encode), encode))) { //判断是不是GBK
                String s3 = encode;
                return s3;
            }
        } catch (Exception exception3) {
        }
        return ""; //如果都不是,说明输入的内容不属于常见的编码格式。
    }

    /**
     * 获取文件夹下的所有文件名称
     * @param path
     * @return
     */
    public static ArrayList<Object> getAllFile(String path) {

        ArrayList<Object> list = new ArrayList();
        File file = new File(path);//
        File[] files = file.listFiles();
        for (int i = 0; i < files.length; i++) {
            File file1 = files[i];
            String fileName = file1.getName();
/*            String prefix = fileName.substring(fileName.lastIndexOf(".") + 1)
                    .toLowerCase();
            if ("csv".equals(prefix)) {
                list.add(fileName);
            }*/
            list.add(fileName);
        }
        return list;
    }

    //读取json文件
    public static Object readJsonFile(File jsonFile) {
        String jsonStr = "";
        try {
            FileReader fileReader = new FileReader(jsonFile);
            Reader reader = new InputStreamReader(new FileInputStream(jsonFile),"utf-8");
            int ch = 0;
            StringBuffer sb = new StringBuffer();
            while ((ch = reader.read()) != -1) {
                sb.append((char) ch);
            }
            fileReader.close();
            reader.close();
            jsonStr = sb.toString();

            JSONObject jsonObject = JSONObject.parseObject(jsonStr);
            return jsonObject;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 写出json文件
     */
    public static void writeJsonFileByString(String newJsonString, String path){
        try {
            FileWriter fw = new FileWriter(path);
            PrintWriter out = new PrintWriter(fw);
            out.write(newJsonString);
            out.println();
            fw.close();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 由于遇到文件夹不查询其包含所有子文件夹、文件,因此没必要用到递归
     *
     * @param dirAllStrArr
     * @param dirFile
     * @return
     * @throws Exception
     */
    public static void DirAll(List<String> dirAllStrArr, File dirFile,Map map) throws Exception {
        if (dirFile.exists()) {
            File files[] = dirFile.listFiles();
            for (File file : files) {
                // 如果遇到文件夹则递归调用。
                if (file.isDirectory()) {
                    System.out.println("-------文件夹-----"+file.getName());
                    // 递归调用
                    DirAll(dirAllStrArr, file,map);
                } else {
                    // 如果遇到文件夹则放入数组
                    if (dirFile.getPath().endsWith(File.separator)) {
                        System.out.println("------2------"+file.getName());
                        dirAllStrArr.add(dirFile.getPath()+ File.separator + file.getName());
                    } else {
                        System.out.println("------文件-----"+file.getName());
                        dirAllStrArr.add(dirFile.getPath() + File.separator
                                + file.getName());

/*                        boolean flay=map.containsKey(file.getName());
                        if (true==flay){//已存在重名文件
                            System.out.println("-------已存在重名文件------");
                        }*/
                        map.put(file.getName(),file.getName());
                    }
                }
            }
        }
    }

    /**
     * 获取文件夹下 所有文件夹的名称
     * @param filePath
     */
    private static void getFilePath(String filePath) {
        File file = new File(filePath);
        if (file.isDirectory()){
            System.out.println("---------------:"+filePath);
            File[] listFiles = file.listFiles();
            for (int i = 0 ;i<listFiles.length;i++){
                getFilePath(listFiles[i].getAbsolutePath());
            }
        }
    }


    public static void isDirectory(File file) {

        if(file.exists()){

            if (file.isFile()) {
                System.out.println("file is ==>>" + file.getAbsolutePath());

            }else{
                File[] list = file.listFiles();
                if (list.length == 0) {
                    System.out.println(file.getAbsolutePath() + " is null");
                } else {
                    for (int i = 0; i < list.length; i++) {
                        isDirectory(list[i]);//递归调用
                    }
                }
            }
        }else{
            System.out.println("文件不存在!");
        }

    }

    /*
     * 函数名:getFile
     * 作用:使用递归,输出指定文件夹内的所有文件
     * 参数:path:文件夹路径   deep:表示文件的层次深度,控制前置空格的个数
     * 前置空格缩进,显示文件层次结构
     */
    private static void getFile(String path,int deep){
        // 获得指定文件对象
        File file = new File(path);
        // 获得该文件夹内的所有文件
        File[] array = file.listFiles();

        for(int i=0;i<array.length;i++)
        {
            if(array[i].isFile())//如果是文件
            {
                for (int j = 0; j < deep; j++)//输出前置空格
                    System.out.print(" ");
                // 只输出文件名字
                System.out.println("1:"+ array[i].getName()+"  文件大小:"+array[i].length());
                // 输出当前文件的完整路径
                // System.out.println("#####" + array[i]);
                // 同样输出当前文件的完整路径   大家可以去掉注释 测试一下
                // System.out.println(array[i].getPath());
            }
            else if(array[i].isDirectory())//如果是文件夹
            {
                for (int j = 0; j < deep; j++)//输出前置空格
                    System.out.print(" ");

                System.out.println("2:"+ array[i].getName()+"  文件大小:"+array[i].length());
                //System.out.println(array[i].getPath());
                //文件夹需要调用递归 ,深度+1
                getFile(array[i].getPath(),deep+1);
            }
        }
    }

    /**
     * 获取文件夹里面所有文件的路径
     * @param path
     * @return
     */
    public static JSONArray getDirectoryFilesPath(String path) {
        File dirFile = new File(path);

        Map<String, JSONArray> map = new HashMap<>();

        if (dirFile.exists()) {
            File files[] = dirFile.listFiles();
            for (File file : files) {
                String createTime = getFileTime(file, "createTime");
                String lastmodfiyTime = getFileTime(file, "lastmodfiyTime");
                // 如果遇到文件夹则递归调用。
                if (file.isDirectory()) {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("type",0);
                    jsonObject.put("fileName",file.getName());

                    //long size=getFileSize3(file);

                    jsonObject.put("length", "");
                    jsonObject.put("createTime",createTime);
                    jsonObject.put("lastmodfiyTime",lastmodfiyTime);
                    jsonObject.put("path",dirFile.getPath()+ File.separator + file.getName());

                    if (map.containsKey(createTime)) {
                        JSONArray array = map.get(createTime);
                        array.add(jsonObject);
                    } else {
                        JSONArray array = new JSONArray();
                        array.add(jsonObject);
                        map.put(createTime,array);
                    }
                    // 递归调用
                    //DirAll(file);
                } else {
                    // 如果遇到文件夹则放入数组
                    if (dirFile.getPath().endsWith(File.separator)) {

                    } else {
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("type",1);
                        jsonObject.put("fileName",file.getName());
                        jsonObject.put("length",FileUtils.getPrintSize(file.length()));
                        jsonObject.put("createTime",createTime);
                        jsonObject.put("lastmodfiyTime", lastmodfiyTime);
                        jsonObject.put("path",dirFile.getPath() + File.separator
                                + file.getName());

                        if (map.containsKey(createTime)) {
                            JSONArray array = map.get(createTime);
                            array.add(jsonObject);
                        } else {
                            JSONArray array = new JSONArray();
                            array.add(jsonObject);
                            map.put(createTime,array);
                        }
                    }
                }
            }
        }
        // 设置一个全局动态数组,来存放文件路径
        // 主要遍历文件夹,包含所有子文件夹、文件的情况时,用到递归,所以要这样设置
        JSONArray dirAllStrArr = new JSONArray();

        Object[] key_arr = map.keySet().toArray();//按创建时间排序
        Arrays.sort(key_arr);
        for  (Object key : key_arr) {
            JSONArray value = map.get(key);
            dirAllStrArr.addAll(value);
        }

        return dirAllStrArr;
    }

    /**
     * 通过file.nio.*中的FileChannel工具来获取文件大小:
     * @param file
     */
    public static long getFileSize3(File file){
        FileChannel fc = null;
        long size=0;
        try{
            if(file.exists() &&file.isFile()){
                String fileName =file.getName();
                FileInputStream fis = new FileInputStream(file);
                fc =fis.getChannel();
                size=fc.size();
                System.out.println("文件"+fileName+"的大小是:"+fc.size()+"\n");

            }

        } catch(Exception e) {
            e.printStackTrace();

        }finally{
            if(null!=fc){
                try{
                    fc.close();
                } catch(IOException e) {
                    e.printStackTrace();

                }

            }
        }
        return size;
    }

    /**
     * 如何获取文件的创建时间、更新时间
     * @param file
     * @return
     */
    public static String getFileTime(File file,String type) {
        if (file == null) {
            return null;
        }

        BasicFileAttributes attr = null;
        try {
            Path path =  file.toPath();
            attr = Files.readAttributes(path, BasicFileAttributes.class);
        } catch (IOException e) {
            e.printStackTrace();
        }

        Instant instant;
        if ("createTime".equals(type)){
            // 创建时间
            instant = attr.creationTime().toInstant();
        }else{
            // 更新时间
            instant = attr.lastModifiedTime().toInstant();
        }

        // 上次访问时间
//        Instant instant = attr.lastAccessTime().toInstant();
        String format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(ZoneId.systemDefault()).format(instant);
        return format;
    }

    /**
     * 在文件处理的系统中,很容易就能通过一些系统自带的方法取出其大小,问题是这个大小往往只是一个字节数B。
     如果要把这个字节数转化为KB、MB、GB的最终呈现给用户,则涉及到整除与取余的算术运算。
     * @param size
     * @return
     */
    public static String getPrintSize(long size) {
        //如果字节数少于1024,则直接以B为单位,否则先除于1024,后3位因太少无意义
        if (size < 1024) {
            return String.valueOf(size) + "B";
        } else {
            size = size / 1024;
        }
        //如果原字节数除于1024之后,少于1024,则可以直接以KB作为单位
        //因为还没有到达要使用另一个单位的时候
        //接下去以此类推
        if (size < 1024) {
            return String.valueOf(size) + "KB";
        } else {
            size = size / 1024;
        }
        if (size < 1024) {
            //因为如果以MB为单位的话,要保留最后1位小数,
            //因此,把此数乘以100之后再取余
            size = size * 100;
            return String.valueOf((size / 100)) + "."
                    + String.valueOf((size % 100)) + "MB";
        } else {
            //否则如果要以GB为单位的,先除于1024再作同样的处理
            size = size * 100 / 1024;
            return String.valueOf((size / 100)) + "."
                    + String.valueOf((size % 100)) + "GB";
        }
    }

    /**
     * 类说明:File流转为MultipartFile流
     * @param file
     * @return
     */
    public static MultipartFile getMulFileByFile(File file) {
        FileItem fileItem = createFileItem(file.getPath(),file.getName());
        MultipartFile mfile = new CommonsMultipartFile(fileItem);
        return mfile;
    }

    public static FileItem createFileItem(String filePath,String fileName){
        String fieldName = "file";
        FileItemFactory factory = new DiskFileItemFactory(16, null);
        FileItem item = factory.createItem(fieldName, "text/plain", false,fileName);
        File newfile = new File(filePath);
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        try
        {
            FileInputStream fis = new FileInputStream(newfile);
            OutputStream os = item.getOutputStream();
            while ((bytesRead = fis.read(buffer, 0, 8192))!= -1)
            {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            fis.close();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return item;
    }

    /**
     * 使用FileInputStream读取文件A的字节,使用FileOutputStream写入到文件B
     * @param source
     * @param dest
     * @throws IOException
     */
    public static void copyFileUsingFileStreams(File source, File dest)
            throws IOException {
        InputStream input = null;
        OutputStream output = null;
        try {
            input = new FileInputStream(source);
            output = new FileOutputStream(dest);
            byte[] buf = new byte[1024];
            int bytesRead;
            while ((bytesRead = input.read(buf))!= -1) {
                output.write(buf, 0, bytesRead);
            }
        } finally {
            input.close();
            output.close();
        }
    }

    /**
     * 写出json文件
     */
    public static void writeJsonFile(String newJsonString, String path){
        try {
            FileWriter fw = new FileWriter(path);
            PrintWriter out = new PrintWriter(fw);
            out.write(newJsonString);
            out.println();
            fw.close();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 读取一个文本 一行一行读取
     *
     * @param path
     * @return
     * @throws IOException
     */
    public static List<String> readFile02(String path) throws IOException {
        // 使用一个字符串集合来存储文本中的路径 ,也可用String []数组
        List<String> list = new ArrayList<String>();
        FileInputStream fis = new FileInputStream(path);
        // 防止路径乱码  如果utf-8 乱码 改GBK   eclipse里创建的txt 用UTF-8,在电脑上自己创建的txt 用GBK
        InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
        BufferedReader br = new BufferedReader(isr);
        String line = "";
        while ((line = br.readLine()) != null) {
            // 如果 t x t文件里的路径 不包含---字符串    这里是对里面的内容进行一个筛选
            if (line.lastIndexOf("---") < 0) {
                list.add(line);
            }
        }
        br.close();
        isr.close();
        fis.close();
        return list;
    }

    /**
     * 把File转化为MultipartFile过程记录
     * @param file
     * @return
     */
    public MultipartFile fileToMultipartFile(File file) {
        FileItem fileItem = createFileItem(file);
        MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
        return multipartFile;
    }

    private static FileItem createFileItem(File file) {
        FileItemFactory factory = new DiskFileItemFactory(16, null);
        FileItem item = factory.createItem("textField", "text/plain", true, file.getName());
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        try {
            FileInputStream fis = new FileInputStream(file);
            OutputStream os = item.getOutputStream();
            while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return item;
    }

    public static void main(String[] args) throws Exception {
/*        File dirFile = new File("C:\\Users\\liangguannan\\Desktop\\download");

        // 设置一个全局动态数组,来存放文件路径
        // 主要遍历文件夹,包含所有子文件夹、文件的情况时,用到递归,所以要这样设置
        ArrayList<String> dirAllStrArr = new ArrayList<String>();
        Map repeatMap = Maps.newHashMap();

        DirAll(dirAllStrArr,dirFile,repeatMap);

        System.out.println("dirAllStrArr:"+dirAllStrArr.size());
        System.out.println("repeatMap:"+repeatMap.size());*/


        //isDirectory(dirFile);

        //getFilePath("C:\\Users\\liangguannan\\Desktop\\csv");

        //这是需要获取的文件夹路径
/*        String path = "C:\\Users\\liangguannan\\Desktop\\csv";
        getFile(path,0);*/

/*        File file = new File("C:\\Users\\liangguannan\\Desktop\\20201215120330.order.json");//
        System.out.println(readJsonFile(file));

        JSONObject jsonObject=(JSONObject) JSONObject.toJSON(readJsonFile(file));
        jsonObject.put("GroupName","wtf");

        writeJsonFile(jsonObject.toJSONString(),"C:\\Users\\liangguannan\\Desktop\\20201215120330.order.json");*/

        //String fileurl="C:\\Users\\liangguannan\\Desktop\\新建文本文档.txt";
        //File sourcefile = new File(fileurl);
        //System.out.println("1:"+sourcefile.getParent());


/*        String file="C:\\Users\\liangguannan\\Desktop\\download\\Script.1.2\\Rpicture.R";
        File destfile = new File(file);

        copyFileUsingFileStreams(sourcefile,destfile);*/
    }
}

package com.hessianhealth.common.utils.file;

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

public class ZipUtils {
    private static final int  BUFFER_SIZE = 2 * 1024;

    /**
     * 压缩成ZIP 方法     * @param srcDir 压缩文件夹路径
     * @param out    压缩文件输出流
     * @param KeepDirStructure  是否保留原来的目录结构,true:保留目录结构;
     *                          false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
     * @throws RuntimeException 压缩失败会抛出运行时异常
     */
    public static void toZip(String srcDir, OutputStream out, boolean KeepDirStructure)
            throws RuntimeException{

        long start = System.currentTimeMillis();
        ZipOutputStream zos = null ;
        try {
            zos = new ZipOutputStream(out);
            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 方法     * @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
     */
    public 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));
            // copy文件到zip输出流中
            int len;
            FileInputStream in = new FileInputStream(sourceFile);
            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);
                    }

                }
            }
        }
    }

    public static void main(String[] args) throws Exception {
        /** 测试压缩方法 */
        FileOutputStream fos1= new FileOutputStream(new File("E:/testZip.zip"));
        ZipUtils.toZip("E:/testZip", fos1,true);

        /** 测试压缩方法 */
        List<File> fileList = new ArrayList<>();
        fileList.add(new File("D:/Java/jdk1.7.0_45_64bit/bin/jar.exe"));
        fileList.add(new File("D:/Java/jdk1.7.0_45_64bit/bin/java.exe"));
        FileOutputStream fos2= new FileOutputStream(new File("c:/mytest02.zip"));
        ZipUtils.toZip(fileList, fos2);
    }
}
package com.hessianhealth.common.utils;

/**
 * Created by liangguannan on 2018/5/4.
 */

import com.alibaba.fastjson.JSONObject;
import com.hessianhealth.common.config.geneConfig;
import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

public class CreateFileUtil {

    /**
     * 获取系统路径
     * @return
     */
    public static String getfilePath(){

		/*不同操作系统的文件创建路径*/
        String filePath = getSaveFilePath(null); //存储文件的父目录位置

        String fileName = null; //存储文件的父目录位置
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");//设置日期格式

        String date=df.format(new Date());

        fileName=filePath+date+"-"+"脑梗死KPI.xlsx";

        return fileName;
    }

    /**
     * 获取保存文件的路径
     *
     * @return
     */
    public static String getSaveFilePath(String fileType) {
        /*不同操作系统的文件创建路径*/
        String filePath = null; //存储文件的父目录位置
        String property = System.getProperty("os.name").toLowerCase();
        System.out.println("系统名称:"+property);
        int indexOf = property.indexOf("windows");
        if (indexOf == 0) {
                /*此处为win系统*/
            String userHome = System.getProperty("user.home");
            filePath = userHome + "\\Desktop\\downFile\\";
            createParentFile(filePath);
        } else {
            /*此处为Linux系统处理*/

            switch(fileType){
                case "image":
                    filePath= geneConfig.getImageUrl();
                    break;
                default:
                    filePath= geneConfig.getUploadPath();
                    break;
            }

            System.out.println("路径名称:"+filePath);
            createParentFile(filePath);
        }

        return filePath;
    }

    /**
     * 根据路径判断文件是否存在,如果不存在则创建
     *
     * @param filePath
     */
    public static void createParentFile(String filePath) {
        File file = new File(filePath);
        boolean exists = file.exists();
        if (exists) {
            boolean directory = file.isDirectory();
            if (directory) {
                file.mkdir();
            }
        } else {
            file.mkdir();
        }
    }

    /**
     * 根据文件路径名称删除文件
     * @param filePath
     * @return
     */
    public static Boolean  delFile(String filePath){
        File file = new File(filePath);
        if (file.exists()) {
            return file.delete();
        }
        return null;
    }

    /**
     * 下载文件
     * @param fileName 文件名称
     * @param fileData 文件的byte
     * @return
     */
    public static ResponseEntity<byte[]> downLoadFile(String fileName, byte[] fileData) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        try {
            headers.setContentDispositionFormData("attachment", new String(fileName.getBytes("utf-8"), "ISO8859-1"));
            return new ResponseEntity<>(fileData,headers, HttpStatus.CREATED);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 传入文件完整路径+文件名称,进行下载
     * 在Controller中直接调用即可
     *
     * @param fileName
     * @return
     */
    public static ResponseEntity<byte[]> downLoadFile(String fileName) {
        File file = new File(fileName);
        if (!file.exists()) {
            System.out.println("-------downLoadFile---------"+"文件不存在");
            return null;
        }
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        try {
            headers.setContentDispositionFormData("attachment", new String(file.getName().getBytes("utf-8"), "ISO8859-1"));
            return new ResponseEntity<>(FileUtils.readFileToByteArray(file),
                    headers, HttpStatus.CREATED);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 生成.json格式文件
     */
    public static boolean createJsonFile(String jsonString, String filePath, String fileName) {
        // 标记文件生成是否成功
        boolean flag = true;

        // 拼接文件完整路径
        String fullPath = filePath + File.separator + fileName + ".json";

        // 生成json格式文件
        try {
            // 保证创建一个新文件
            File file = new File(fullPath);
            if (!file.getParentFile().exists()) { // 如果父目录不存在,创建父目录
                file.getParentFile().mkdirs();
            }
            if (file.exists()) { // 如果已存在,删除旧文件
                file.delete();
            }
            file.createNewFile();

            // 格式化json字符串
            jsonString = JsonFormatTool.formatJson(jsonString);

            // 将格式化后的字符串写入文件
            Writer write = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
            write.write(jsonString);
            write.flush();
            write.close();
        } catch (Exception e) {
            flag = false;
            e.printStackTrace();
        }

        // 返回是否成功的标记
        return flag;
    }


    /**
     * 创建txt 文件
     * @return
     */
    public static void createTxtFile(List<Map<String, String>> contentList, String filePath, String fileName) throws IOException  {

        // 拼接文件完整路径
        String fullPath1 = filePath + File.separator + fileName + "_temp.txt";//生成一个临时文件
        String fullPath = filePath + File.separator + fileName + ".txt";//标准路径

        // 保证创建一个新文件
        File filenameShip = new File(fullPath1);
        if (!filenameShip.getParentFile().exists()) { // 如果父目录不存在,创建父目录
            filenameShip.getParentFile().mkdirs();
        }
        if (filenameShip.exists()) { // 如果已存在,删除旧文件
            filenameShip.delete();
        }

        // 先读取原有文件内容,然后进行写入操作
        String readStr = "\t";//标题以tab 分割
        FileWriter writer = null;
        for (int i = 0; i < contentList.size(); i++) {
            HashMap<String, String> map=(HashMap<String, String>) contentList.get(i);
            String filein1 = "\r\n" ;
            for (int j = 0; j < map.size()-1; j++) {
                filein1+=map.get((1+j)+"")+ readStr;
            }
            filein1+=map.get((map.size())+"");

            filein1+="\r\n";
            try {
                writer = new FileWriter(filenameShip, true);
                writer.write(filein1);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (writer != null) {
                    try {
                        writer.close();
                    } catch (IOException e2) {
                        e2.printStackTrace();
                    }
                }
            }
        }
        readLocalFile(fullPath1,fullPath,contentList.size());
    }

    /**
     * 用Java实现去除文本文件中的空行
     * @param fullPath1
     * @param fullPath
     * @param size
     */
    public static void readLocalFile(String fullPath1, String fullPath, int size){
        String filename1=fullPath1;//该文件有大量的空行
        String filename2=fullPath;//filename1文件被去除空行后,放入文件filename2中
        File file=new File(filename1);
        InputStream is=null;
        BufferedReader br = null;
        String tmp;
        FileWriter writer=null;
        int i=0;

        try {
            is=new BufferedInputStream(new FileInputStream(file));
            br = new BufferedReader(new InputStreamReader(is, "utf-8"));
            writer = new FileWriter(filename2, true);
            while((tmp=br.readLine())!=null){
                if(tmp.equals(""));
                else{

                    if (i ==(size-1)){//从0开始遍历
                        writer.write(tmp);//去除最后一行的空格
                    }else {
                        writer.write(tmp+"\n");
                        i++;
                    }
                }
            }
            writer.close();
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        File filenameShip = new File(fullPath1);//删除临时文件
        filenameShip.delete();
    }

    public static void readLocalFile111(String[] args){

        String line=null;
        int i=0;
        File file=new File(args[0]);//用命令行参数直接写入待处理文件
        File file1=new File(args[1]);
        //判断输入的是否是TXT文档,不是则提示退出
        if(args[0].endsWith("txt")&args[1].endsWith("txt"))
        {
            //判断输入的文档是否存在,不存在则提示退出
            if(!file.exists())
            {
                System.out.println("文件不存在!");
                System.exit(0);
            }
            //输入的是TXT文档则继续往下执行
            try
            {
                Runtime.getRuntime().exec("notepad "+args[0]);//打开待处理文件
                //读出文档数据流方式
                InputStreamReader Stream=new InputStreamReader(new FileInputStream(file),"UTF-8");//读入数据流方式设为‘UTF-8’,避免乱码
                //构造一个字符流的缓存器,存放在控制台输入的字节转换后成的字符
                BufferedReader reader=new BufferedReader(Stream);
                //写入数据流方式
                OutputStreamWriter outStream=new OutputStreamWriter(new FileOutputStream(file1),"UTF-8");
                BufferedWriter writer=new BufferedWriter(outStream);
                //以行读出文档内容至结束
                while((line=reader.readLine())!=null)
                {
                    if(line.equals(""))//判断是否是空行
                    {
                        continue;//是空行则不进行操作
                    }
                    else
                    {
                        i++;
                        writer.write("["+i+"]");//可在文档中标出行号
                        writer.write(line+"\r\n");//将非空白行写入新文档
                    }
                }
                //关闭数据流
                writer.close();
                reader.close();
                System.out.println("修改完成!");
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
            try{
                //打开修改后的文档
                Runtime.getRuntime().exec("notepad "+args[1]);
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
        }
        else
        {
            System.out.println("输入错误!(非.txt)");
            System.exit(0);//退出程序
        }
    }


    /**
     * 通过本地文件访问json并读取
     * @param path:E:/svn/05.Hospital/templatedept_uuid.json
     * @return:json文件的内容
     */
    public static String ReadFile(String path){
        String laststr="";
        File file=new File(path);// 打开文件
        BufferedReader reader=null;
        try{
            FileInputStream in = new FileInputStream(file);
            reader=new BufferedReader(new InputStreamReader(in,"UTF-8"));// 读取文件
            String tempString=null;
            while((tempString=reader.readLine())!=null){
                laststr=laststr+tempString;
            }
            reader.close();
        }catch(IOException e){
            e.printStackTrace();
        }finally{
            if(reader!=null){
                try{
                    reader.close();
                }catch(IOException el){
                }
            }
        }
        return laststr;
    }

    /**
     * 读取某个文件夹下的所有文件
     */
    public static List<JSONObject> readfile(String filepath) throws FileNotFoundException, IOException {
        List<JSONObject> list= new ArrayList();

        try {
            File file = new File(filepath);
            if (!file.isDirectory()) {
                System.out.println("文件");
                System.out.println("path=" + file.getPath());
                System.out.println("absolutepath=" + file.getAbsolutePath());
                System.out.println("name=" + file.getName());

            } else if (file.isDirectory()) {
                System.out.println("文件夹");
                String[] filelist = file.list();
                for (int i = 0; i < filelist.length; i++) {
                    File readfile = new File(filepath + "\\" + filelist[i]);
                    if (!readfile.isDirectory()) {
                        System.out.println("path=" + readfile.getPath()+"========="+readfile.getName());

                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("path",readfile.getPath());
                        jsonObject.put("name",readfile.getName());

                        //getAllItems(readfile.getPath(),readfile.getName());

                        list.add(jsonObject);

                    } else if (readfile.isDirectory()) {
                        readfile(filepath + "\\" + filelist[i]);
                    }
                }

            }

        } catch (FileNotFoundException e) {
            System.out.println("readfile()   Exception:" + e.getMessage());
        }
        return list;
    }

    /**
     * 去除txt中的空行
     *
     */
    public static void qukonghang () {
        String filename1="C:\\home\\data\\config\\20210908163757\\20210908163757_rename.txt";
        String filename2="C:\\home\\data\\config\\20210908163757\\20210908163757_rename1234.txt";

        File file=new File(filename1);

        InputStream is=null;

        BufferedReader br = null;

        String tmp;

        FileWriter writer=null;

        int i=0;

        try {
            is=new BufferedInputStream(new FileInputStream(file));

            br = new BufferedReader(new InputStreamReader(is, "utf-8"));

            writer = new FileWriter(filename2, true);

            while((tmp=br.readLine())!=null){

                System.out.println(i+"-----:"+tmp.trim());

                if(tmp.trim().equals(""));
                else{
                    if (i ==2){
                        writer.write(tmp);
                    }else {
                        writer.write(tmp+"\n");
                        i++;
                    }

                }
            }
            writer.close();
            is.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 直接读取txt的最后一行
     * @param file
     * @param charset
     * @return
     * @throws IOException
     */
    public static String readLastLine(File file, String charset) throws IOException {
        if (!file.exists() || file.isDirectory() || !file.canRead()) {
            return null;
        }
        RandomAccessFile raf = null;
        try {
            raf = new RandomAccessFile(file, "r");
            long len = raf.length();
            if (len == 0L) {
                return "";
            } else {
                long pos = len - 1;
                while (pos > 0) {
                    pos--;
                    raf.seek(pos);
                    if (raf.readByte() == '\n') {
                        break;
                    }
                }
                if (pos == 0) {
                    raf.seek(0);
                }
                byte[] bytes = new byte[(int) (len - pos)];
                raf.read(bytes);
                if (charset == null) {
                    return new String(bytes);
                } else {
                    return new String(bytes, charset);
                }
            }
        } catch (FileNotFoundException e) {
        } finally {
            if (raf != null) {
                try {
                    raf.close();
                } catch (Exception e2) {
                }
            }
        }
        return null;
    }

    /**
     * 循环创建新文件
     * @param filePath
     * @return
     */
    public static void createNewFile( String filePath)throws IOException {
        File checkFile = new File(filePath);
        try {
            // 二、检查目标文件是否存在,不存在则创建
            if (!checkFile.getParentFile().exists()) {
                checkFile.getParentFile().mkdirs();// 创建多级目标文件
            }

            if (!checkFile.exists()) {
                checkFile.createNewFile();//创建文件
            }else {
                checkFile.delete();
                checkFile.createNewFile();//创建文件
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /*
    * 复制单个文件
    * @param oldPath String 原文件路径 如:c:/fqf.txt
    * @param newPath String 复制后路径 如:f:/fqf.txt
    * @return boolean
    */
    public static void copyFile(String oldPath, String newPath) {
        try {
            int bytesum = 0;
            int byteread = 0;
            File oldfile = new File(oldPath);
            if (oldfile.exists()) { //文件存在时

                File file = new File(newPath);
                if (!file.exists()){//如果文件不存在
                    createNewFile(newPath);
                }

                InputStream inStream = new FileInputStream(oldPath); //读入原文件
                FileOutputStream fs = new FileOutputStream(newPath);
                byte[] buffer = new byte[1444];
                int length;
                while ( (byteread = inStream.read(buffer)) != -1) {
                    bytesum += byteread; //字节数 文件大小
                    System.out.println(bytesum);
                    fs.write(buffer, 0, byteread);
                }
                inStream.close();
            }
        }
        catch (Exception e) {
            System.out.println("复制单个文件操作出错");
            e.printStackTrace();

        }

    }

    /**
     * 复制整个文件夹内容
     * @param oldPath String 原文件路径 如:c:/fqf
     * @param newPath String 复制后路径 如:f:/fqf/ff
     * @return boolean
     */
    public static void copyFolder(String oldPath, String newPath) {

        try {
            (new File(newPath)).mkdirs(); //如果文件夹不存在 则建立新文件夹
            File a=new File(oldPath);
            String[] file=a.list();
            File temp=null;
            for (int i = 0; i < file.length; i++) {
                if(oldPath.endsWith(File.separator)){
                    temp=new File(oldPath+file[i]);
                }
                else{
                    temp=new File(oldPath+File.separator+file[i]);
                }

                if(temp.isFile()){
                    FileInputStream input = new FileInputStream(temp);
                    FileOutputStream output = new FileOutputStream(newPath + "/" +
                            (temp.getName()).toString());
                    byte[] b = new byte[1024 * 5];
                    int len;
                    while ( (len = input.read(b)) != -1) {
                        output.write(b, 0, len);
                    }
                    output.flush();
                    output.close();
                    input.close();
                }
                if(temp.isDirectory()){//如果是子文件夹
                    copyFolder(oldPath+"/"+file[i],newPath+"/"+file[i]);
                }
            }
        }
        catch (Exception e) {
            System.out.println("复制整个文件夹内容操作出错");
            e.printStackTrace();

        }

    }

    public static void main(String[] args) {

        try {
            qukonghang();


/*            String filePath ="C:\\Users\\liangguannan\\Desktop";

            // 标题
            List<Map<String, String>> list2 = new ArrayList<Map<String, String>>();
            HashMap<String, String> map = new HashMap<String, String>();
            map.put("1", "序号");
            map.put("2", "姓名");
            list2.add(map);
            // 内容
            List<Map<String, String>> dataList = new ArrayList<Map<String, String>>();
            Map<String, String> dataMap = new HashMap<String, String>();
            dataMap.put("num", "1");
            dataMap.put("name", "张三");
            dataList.add(dataMap);
            dataMap = new HashMap<String, String>();
            dataMap.put("num", "2");
            dataMap.put("name", "李四");
            dataList.add(dataMap);

            for (Map<String, String> m : dataList) {
                HashMap<String, String> map2 = new HashMap<String, String>();
                map2.put("1", m.get("num"));
                map2.put("2", m.get("name"));
                list2.add(map2);
            }
            createTxtFile(list2, filePath,"pro");*/

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值