首页 > 其他分享 >文件处理工具

文件处理工具

时间:2023-10-08 17:25:35浏览次数:34  
标签:文件 String 处理 File new import 工具 null out

package com.thtf.zwdsj.fangjia.utils;

import com.thtf.zwdsj.code.common.exception.CommonException;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.io.IOUtils;
import org.springframework.http.MediaType;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.*;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
 * @BelongsProject: xiaozhire0goods
 * @BelongsPackage: com.lzq.demoUse
 * @Author: 小智RE0 --- 学习记录
 * @Date: 2022/12/8 21:36
 * @Description: TODO
 */
public class FileMutilUnZip {


    //处理解压zip
    public static List<Path> dealUnZip(String zipPath, String targetZipPath) {
        List<Path> sourcesList = new ArrayList<>();
        if (zipPath.endsWith(".zip")) {
            dealzip(zipPath, targetZipPath);
        }
        try (Stream<Path> paths = Files.walk(Paths.get(targetZipPath))) {
            List<Path> result = paths
                    .filter(Files::isRegularFile)
                    .collect(Collectors.toList());
//            result.forEach(System.out::println);
            for (int i = 0; i < result.size(); i++) {
                String filePath = result.get(i).toString();
                if (filePath.endsWith(".zip")) {
//                    System.out.println(filePath);
                    dealzip(filePath, result.get(i).getParent().toString() + "/");
                    File deleteFile = new File(filePath);
                    deleteFile.delete();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        try (Stream<Path> paths = Files.walk(Paths.get(targetZipPath))) {
            List<Path> result = paths
                    .filter(Files::isRegularFile)
                    .collect(Collectors.toList());
//            result.forEach(System.out::println);
//            for (int i = 0; i <result.size() ; i++) {
//                String filePath = result.get(i).toString();
//                if (filePath.endsWith(".xlsx") || filePath.endsWith(".xls")) {
//                    String fileName1 = result.get(i).getFileName().toString();
//                    String fileName = System.currentTimeMillis() + "_" + result.get(i).getFileName();
//                    System.out.println(fileName1);
//                    System.out.println(fileName);
//                }
//            }
            return result;
        } catch (IOException e) {
            e.printStackTrace();
        }

        return sourcesList;
    }

    //处理文件解压;
    public static void dealzip(String zipSourcePath, String targetZipPath) {
        //判断目标地址是否存在,如果没有就创建
        File pathFile = new File(targetZipPath);
        if (!pathFile.exists()) {
            pathFile.mkdirs();
        }
        ZipFile zipFile = null;
        try {
            zipFile = new ZipFile(zipSourcePath, Charset.forName("gbk"));
            //若zip中含有中文名文件,换GBK
            //zip = new ZipFile(zipPath, Charset.forName("GBK"));
            //遍历里面的文件及文件夹
            Enumeration entries = zipFile.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = (ZipEntry) entries.nextElement();
                String zipEntryName = entry.getName();
                InputStream in = zipFile.getInputStream(entry);
                //也就是把这个文件加入到目标文件夹路径;
                String outpath = (targetZipPath + zipEntryName).replace("/", File.separator);
                //String outpath = targetZipPath.replace("/", File.separator);
                //不存在则创建文件路径
                File file = new File(outpath.substring(0, outpath.lastIndexOf(File.separator)));
                if (!file.exists()) {
                    file.mkdirs();
                }
                File outPathFile = new File(outpath);
                //文件夹就不解压;
                if (outPathFile.isDirectory()) {
                    continue;
                }
                OutputStream out = new FileOutputStream(outpath);
                byte[] bf = new byte[2048];
                int len;
                while ((len = in.read(bf)) > 0) {
                    out.write(bf, 0, len);
                }
                in.close();
                out.close();
            }
            zipFile.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 将MultipartFile转换为File
     *
     * @param outFilePath 参数
     * @param multiFile   参数
     * @return 执行结果
     */
    public static File multipartFileToFile(String outFilePath, MultipartFile multiFile) {
        // 获取文件名
        if (null == multiFile) {
            return null;
        }
        String fileName = multiFile.getOriginalFilename();
        if (null == fileName) {
            return null;
        }
        try {
            File toFile;
            InputStream ins;
            ins = multiFile.getInputStream();
            //指定存储路径
            toFile = new File(outFilePath.concat(File.separator).concat(multiFile.getOriginalFilename()));
            inputStreamToFile(ins, toFile);
            return toFile;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static MultipartFile getMultipartFileByInputStream(InputStream input, String fileName) {
        FileItem item = new DiskFileItemFactory().createItem("file"
                , MediaType.MULTIPART_FORM_DATA_VALUE
                , true
                , fileName);
        try (
                OutputStream os = item.getOutputStream()) {
            // 流转移
            IOUtils.copy(input, os);
        } catch (Exception e) {
            throw new IllegalArgumentException("Invalid file: " + e, e);
        }
        return new CommonsMultipartFile(item);
    }

    public static MultipartFile getMultipartFile(File file) {
        FileItem item = new DiskFileItemFactory().createItem("file"
                , MediaType.MULTIPART_FORM_DATA_VALUE
                , true
                , file.getName());
        try (InputStream input = new FileInputStream(file);
             OutputStream os = item.getOutputStream()) {
            // 流转移
            IOUtils.copy(input, os);
        } catch (Exception e) {
            throw new IllegalArgumentException("Invalid file: " + e, e);
        }

        return new CommonsMultipartFile(item);
    }

    public static List<File> getAllFile(File dirFile) {
        // 如果文件夹不存在或着不是文件夹,则返回 null
        if (Objects.isNull(dirFile) || !dirFile.exists() || dirFile.isFile())
            return null;

        File[] childrenFiles = dirFile.listFiles();
        if (Objects.isNull(childrenFiles) || childrenFiles.length == 0)
            return null;

        List<File> files = new ArrayList<>();
        for (File childFile : childrenFiles) {
            // 如果是文件,直接添加到结果集合
            if (childFile.isFile()) {
                files.add(childFile);
            }
            //以下几行代码取消注释后可以将所有子文件夹里的文件也获取到列表里
//            else {
//                // 如果是文件夹,则将其内部文件添加进结果集合
//                List<File> cFiles = getAllFile(childFile);
//                if (Objects.isNull(cFiles) || cFiles.isEmpty()) continue;
//                files.addAll(cFiles);
//            }
        }
        return files;
    }

    public static MultipartFile[] getMultipartFileList(String path) {
        File file = new File(path);
        List<File> allFile = getAllFile(file);
        List<MultipartFile> multipartFileList = new ArrayList<>();
        for (File file1 : allFile) {
            multipartFileList.add(getMultipartFile(file1));
        }
        return multipartFileList.toArray(new MultipartFile[multipartFileList.size()]);
    }

    public static void inputStreamToFile(InputStream ins, File file) {
        try (OutputStream os = new FileOutputStream(file)) {
            int bytesRead;
            int bytes = 8192;
            byte[] buffer = new byte[bytes];
            while ((bytesRead = ins.read(buffer, 0, bytes)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Map<String, String> parsePath(Path path) {
        Map result = new HashMap<String, String>();
        String[] str = path.toString().split("/");
        if (str.length == 1) {
            str = path.toString().split("\\\\");
        }
        List<String> collect = Arrays.stream(str).filter(s -> s.contains("_")).collect(Collectors.toList());
        if (collect.size() == 0) throw new CommonException("无法解析路径");
        for (String s : collect) {
            String[] split = s.split("_");
            boolean splitHead = Pattern.matches("^[0-9]*$", split[0]);
            boolean splitTail = Pattern.matches("^[0-9]*$", split[1]);
            if (splitHead && splitTail) {
                result.put("reportPeriod", split[0]);
                result.put("zonePosition", split[1]);
                return result;
            }
        }
        return result;
    }


}
package com.thtf.zwdsj.fangjia.utils;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @创建人 qinyangyang
 * @创建时间 2022/11/7
 * @描述
 */
public class FileUtil {

    /**
     * 功能:压缩多个文件,输出压缩后的zip文件流
     *
     * @param sourcePath:源文件路径
     * @param zipFileName:压缩后的文件名
     * @param response:           Http响应
     */
    public static void zipFiles(String sourcePath, String zipFileName, HttpServletResponse response) throws IOException {
        File[] files = new File(sourcePath).listFiles();
        byte[] buf = new byte[1024];
        // 获取输出流
        BufferedOutputStream bos = null;
        try {
            bos = new BufferedOutputStream(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        FileInputStream in = null;
        ZipOutputStream out = null;
        try {
            response.reset(); // 重点突出
            // 不同类型的文件对应不同的MIME类型
            response.setContentType("application/x-msdownload");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment;filename=" + zipFileName + ".zip");

            // ZipOutputStream类:完成文件或文件夹的压缩
            out = new ZipOutputStream(bos);
            for (int i = 0; i < files.length; i++) {
                in = new FileInputStream(files[i]);
                // 给列表中的文件单独命名
                out.putNextEntry(new ZipEntry(files[i].getName()));
                int len = -1;
                while ((len = in.read(buf)) != -1) {
                    out.write(buf, 0, len);
                }
            }
            System.out.println("压缩完成.");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.flush();
                out.close();
            }
            if (bos != null) {
                bos.flush();
                bos.close();
            }
        }
    }

    /**
     * 功能:压缩多个文件,输出压缩后的zip 返回路径
     * @param sourcePath
     * @param zipFileName
     * @return
     * @throws IOException
     */
    public static String zipFile(String sourcePath, String zipFileName) throws IOException {
        String outPath = sourcePath + "/" + zipFileName + ".zip";
        File[] files = new File(sourcePath).listFiles();
        byte[] buf = new byte[1024];
        // 获取输出流
        BufferedOutputStream bos = null;
        try {
            bos = new BufferedOutputStream(new FileOutputStream(outPath));
        } catch (IOException e) {
            e.printStackTrace();
        }
        FileInputStream in = null;
        ZipOutputStream out = null;
        try {
            // ZipOutputStream类:完成文件或文件夹的压缩
            out = new ZipOutputStream(bos);
            for (int i = 0; i < files.length; i++) {
                in = new FileInputStream(files[i]);
                // 给列表中的文件单独命名
                out.putNextEntry(new ZipEntry(files[i].getName()));
                int len = -1;
                while ((len = in.read(buf)) != -1) {
                    out.write(buf, 0, len);
                }
            }
            System.out.println("压缩完成.");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.flush();
                out.close();
            }
            if (bos != null) {
                bos.flush();
                bos.close();
            }
        }
        return outPath;
    }

    public static void deleteFile(File file) {
        File[] files = file.listFiles();
        if (files != null) {//如果包含文件进行删除操作
            for (int i = 0; i < files.length; i++) {
                if (files[i].isFile()) {
                    //删除子文件
                    files[i].delete();
                } else if (files[i].isDirectory()) {
                    //通过递归的方法找到子目录的文件
                    deleteFile(files[i]);
                }
                files[i].delete();//删除子目录
            }
        }
    }

    public static void isExist(String outPath) {
        File outFile = new File(outPath);
        if (!outFile.exists()) {
            try {
                outFile.mkdirs();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}

老式xls

package com.thtf.zwdsj.fangjia.utils;

import com.thtf.zwdsj.fangjia.utils.excelUtils.ExcelImport;
import jxl.Sheet;
import jxl.Workbook;
import jxl.WorkbookSettings;

import java.io.File;
import java.lang.reflect.Field;
import java.util.*;

public class JxlUtils {

    /**
     * @param encoding 出现中文 需要 gbk 无 utf8
     * @throws Exception
     */
    public static List<Map<String, Object>> exportXls(File file, String encoding) throws Exception {
        List<Map<String, Object>> data = new ArrayList();
        List header = new ArrayList();
        WorkbookSettings workbookSettings = new WorkbookSettings();
        workbookSettings.setEncoding(encoding);//防止乱码情况
        // 1. 打开 Excel 文件
        Workbook workbook = Workbook.getWorkbook(file, workbookSettings);
        // 2. 获取第一个工作表 Sheet
        Sheet sheet = workbook.getSheet(0);
        // 3. 遍历所有行和列,并打印单元格内容
        for (int row = 0; row < sheet.getRows(); row++) {
            Map rowData = new HashMap();
            for (int col = 0; col < sheet.getColumns(); col++) {
                if (row == 0) {
                    header.add(sheet.getCell(col, row).getContents());
                } else {
                    rowData.put(header.get(col), sheet.getCell(col, row).getContents());
                }
            }
            if (row > 0) {
                data.add(rowData);
            }
        }
        // 4. 关闭 Excel 文件
        workbook.close();
        return data;
    }

    /**
     * ExcelImport 对象
     *
     * @param t
     * @param dataMap
     * @return
     */
    public static Map<String, Object> getValue(Class t, Map<String, Object> dataMap) {
        Map<String, Object> data = new HashMap<>();
        Field[] fields = t.getDeclaredFields();
        Arrays.stream(fields).forEach(item -> {
            ExcelImport annotation = item.getAnnotation(ExcelImport.class);
            if (annotation != null) {
                String value = annotation.value();
                if (value.contains(",")) {
                    String[] split = value.split(",");
                    for (String s : split) {
                        if (dataMap.get(s) == null) continue;
                        data.put(item.getName(), dataMap.get(s));
                    }
                } else {
                    data.put(item.getName(), dataMap.get(value));
                }
            }
        });
        return data;
    }

    public static List<Map<String, Object>> conversion(File file, String encoding, Class t) throws Exception {
        List data = new ArrayList();
        List<Map<String, Object>> mapList = exportXls(file, encoding);
        for (Map<String, Object> map : mapList) {
            data.add(getValue(t, map));
        }
        return data;
    }

}

 

标签:文件,String,处理,File,new,import,工具,null,out
From: https://www.cnblogs.com/chenTo/p/17749661.html

相关文章

  • android: 通过Intent筛选多种类型文件
     一般使用setType()方法来实现文件过滤,如:只显示PDF文件:intrequestCode=100;Intentintent=newIntent(Intent.ACTION_GET_CONTENT);intent.setType("application/pdf");intent.addCategory(Intent.CATEGORY_OPENABLE);startActivityFor......
  • 虚拟化技术之kvm管理工具virsh常用基础命令(二)
    上一篇博客我们主要聊了下virsh管理kvm虚拟机的命令相关用法和说明,回顾请参考https://www.cnblogs.com/qiuhom-1874/p/13508231.html;今天我们来继续说virsh管理kvm虚拟机的话题;1、virsh监控kvm虚拟机相关命令virsh domblklist:列出指定虚拟机上的磁盘信息......
  • py文件运行闪退
     于是乎用cmd命令执行得到结果:Traceback(mostrecentcalllast):File"waterRPA.py",line1,in<module>importpyautoguiModuleNotFoundError:Nomodulenamed'pyautogui'之前这个py文件明明可以正常运行的看到提示Nomodulenamed'pyautogui'显然是p......
  • 安全工具合集:125个最佳网络安全工具-SecToolsOrg
    SecToolsOrg是什么SecToolsOrg是一个国外网友创建的安全工具网站,收集了125个最佳网络安全工具,网站为英文语言,网站提供评级、评论、搜索、排序和新工具建议表,该站点允许在任何平台上使用开源和商业工具,每款软件工具都有详细的介绍截图等等,感兴趣的同学可以到网站学习。英文页面......
  • 记一次Smanga 任意文件读取漏洞挖掘(CVE-2023-36077)
    记录一次本人CVE漏洞挖掘的过程,此漏洞已被分配编号:CVE-2023-36077引言水一篇文章,本文介绍了对一个开源项目的未授权任意文件读取漏洞的挖掘,此开源项目是一个流媒体管理平台。漏洞原理源码处使用了PHP函数file_get_contents读取文件内容,接收的参数file通过POST直接传入,没有......
  • js+php分片上传大文件
    1.理解部分 服务端为什么不能直接传大文件?跟php.ini里面的几个配置有关upload_max_filesize=2M//PHP最大能接受的文件大小post_max_size=8M//PHP能收到的最大POST值'memory_limit=128M//内存上限max_execution_time=30//最大执行时间当然不能简单粗暴的把上面......
  • CVE-2020-10977_GitLab任意文件读取导致RCE漏洞复现
    CVE-2020-10977_GitLab任意文件读取导致RCE漏洞复现0x01环境安装1yum-yinstallpolicycoreutilsopenssh-serveropenssh-clientspostfix分配给虚拟机的物理内存最好是4G。下载gitlab安装包CE下载地址:https://packages.gitlab.com/gitlab/gitlab-ceEE下......
  • jmeter 两个"csv数据文件设置"遍历数据,实现多用户购买多个商品
    目标使用jmeter构造基础数据,需要实现多个用户购买多个商品的场景。 数据准备1号数据txt文件,包含token和userId,用于用户登录(有10个用户的登录信息);2号数据txt文件,包含goodsId,用户购买商品(有6个商品的Id); jmeter设置1.添加--配置元件--“CSV数据文件设置“用于读取token和u......
  • 【多线程笔记】多线程处理队列数据
    usingSystem.Collections.Concurrent;usingSystem.Diagnostics;{intthreadCount=20;List<Task>tasks=newList<Task>();ConcurrentQueue<int>queues=newConcurrentQueue<int>();for(inti=0;i<1000;i++)......
  • chrome调试工具之[hover悬浮样式]
    前言在调节带有hover样式的元素时,当鼠标移动到上面的时候才会显示相应的元素,鼠标移开时元素就会消失,所以导致无法调节样式问题,第一种方式方便定位元素位置,第二种方式可以解决问题(可以直接看第二种方法!!!)一、快捷定位元素位置的方法使用网上的方法,首先F12打开调试工具,找到加了h......