FileUtils 文件新建、复制、输出到文件压缩上传下载等

package com.internetware.apistore.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.HashSet;
import java.util.Set;

public class FileUtils {
    private static final Logger LOGGER = LoggerFactory.getLogger(FileUtils.class);
    //复制方法
    public static boolean copyDir(String src, String des)  {
        try {
        //初始化文件复制
        File file1=new File(src);
        if(!file1.exists()){
            return false;
        }else{
        //把文件里面内容放进数组
        File[] fs=file1.listFiles();
        //初始化文件粘贴
        File file2=new File(des);
        //判断是否有这个文件有不管没有创建
        if(!file2.exists()){
            file2.mkdirs();
        }
        //遍历文件及文件夹
        for (File f : fs) {
            if(f.isFile()){
                //文件
                fileCopy(f.getPath(),des+File.separator+f.getName()); //调用文件拷贝的方法
            }else if(f.isDirectory()){
                //文件夹
                copyDir(f.getPath(),des+File.separator+f.getName());//继续调用复制方法      递归的地方,自己调用自己的方法,就可以复制文件夹的文件夹了
            }
        }
            return true;
        }
        }catch (Exception e){
            e.getStackTrace();
            return false;
        }
    }

    /**
     * 文件复制的具体方法
     */
    private static void fileCopy(String src, String des) throws Exception {
        //io流固定格式
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(src));
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(des));
        int i = -1;//记录获取长度
        byte[] bt = new byte[2014];//缓冲区
        while ((i = bis.read(bt))!=-1) {
            bos.write(bt, 0, i);
        }
        bis.close();
        bos.close();
        //关闭流
    }
    public static String getFileName(String fName){
        String fileName = null;
        File tempFile =new File( fName.trim());
        if(tempFile.exists()){
            File[] array = tempFile.listFiles();
            for(int i = 0 ; i<array.length ; i++){
                String houzhui = array[i].toString().substring(array[i].toString().lastIndexOf(".") + 1);
                if(houzhui.equals("iw")||houzhui.equals(".zip")){
                    fileName = array[i].getName();
                }
            }
        }
        return fileName;
    }
    /**
     * 删除空目录
     * @param dir 将要删除的目录路径
     */
    private static void doDeleteEmptyDir(String dir) {
        boolean success = (new File(dir)).delete();
        if (success) {
            LOGGER.info("Successfully deleted empty directory: " + dir);
        } else {
            LOGGER.info("Failed to delete empty directory: " + dir);
        }
    }
    public static void main(String[] args) throws Exception {
        String srcPathName = "E:/workSpace/apistore/apistore-api/target/upload"+File.separator+"temp"+File.separator+"123";
        String content = "{\"id\":10,\"versionId\":11,\"name\":\"金融基金\",\"onlineTime\":0,\"version\":\"v1.0\"}";
        writeTxtFile(content,new File(srcPathName));
        getDirName(srcPathName);
                String sourcePath = "C:/Users/jiahuixi/Desktop/upload/temp/apiId";
        String path = "C:/Users/jiahuixi/Desktop/upload/real/apiId";
        doDeleteEmptyDir("new_dir1");
        String newDir2 = "new_dir2";
        boolean success = deleteDir(new File("C:/Users/jiahuixi/Desktop/upload/"));
        if (success) {
            System.out.println("Successfully deleted populated directory: " + newDir2);
        } else {
            System.out.println("Failed to delete populated directory: " + newDir2);
        }

        copyDir(sourcePath, path);
    }

    /**
     * 写入文件
     * @param
     */
    public static boolean writeTxtFile(String content,File  fileName)throws Exception{
        RandomAccessFile mm=null;
        boolean flag=false;
        FileOutputStream o=null;
        try {
            o = new FileOutputStream(fileName);
            o.write(content.getBytes("UTF-8"));
            o.close();
//   mm=new RandomAccessFile(fileName,"rw");
//   mm.writeBytes(content);
            flag=true;
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }finally{
            if(mm!=null){
                mm.close();
            }
        }
        return flag;
    }
    /**
     * 递归删除目录下的所有文件及子目录下所有文件
     * @param dir 将要删除的文件目录
     * @return boolean Returns "true" if all deletions were successful.
     *                 If a deletion fails, the method stops attempting to
     *                 delete and returns "false".
     */
    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 Set<String> getDirName(String fName){
        Set<String> set = new HashSet<>();
        String fileName = null;
        File tempFile =new File( fName.trim());
        if(tempFile.exists()){
            File[] array = tempFile.listFiles();
            for(int i = 0 ; i<array.length ; i++){
                set.add(array[i].getName().toString());
            }
        }
        System.out.println(set);
        return set;
    }
}
package com.internetware.apistore.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.CRC32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 压缩文件工具类
 * @author sun.kai
 * 2016年8月14日
 */
public class ZipUtils {
    static final int BUFFER = 8192;
    private static final Logger LOGGER = LoggerFactory.getLogger(ZipUtils.class);
    private static File zipFile;

    /**
     * 压缩单个或多文件方法
     * @param zipPath 压缩后的文件路径
     * @param srcPathName 要压缩的文件路径
     * 参数srcPathName也可以定义成数组形式,需调用方把参数封装到数组中传过来即可
     */
    public static void compress(String zipPath,String... srcPathName) {
        //压缩后的文件对象
        zipFile = new File(zipPath);
        if (zipFile.getParentFile() != null && !zipFile.getParentFile().exists()) {
            zipFile.getParentFile().mkdirs();
        }
        try {
            //创建写出流操作
            FileOutputStream fileOutputStream = new FileOutputStream(zipFile);
            CheckedOutputStream cos = new CheckedOutputStream(fileOutputStream,new CRC32());
            ZipOutputStream out = new ZipOutputStream(cos);
            for(String srcPath:srcPathName){
                //创建需要压缩的文件对象
                File file = new File(srcPath);
                if (!file.exists()){
                    throw new RuntimeException(srcPath + "不存在!");
                }
                /*
                 * (1)如果在zip压缩文件中不需要一级文件目录,定义String basedir = "";
                 * 下面的compress方法中当判断文件file是目录后不需要加上basedir = basedir + file.getName() + File.separator;
                 * (2)如果只是想在压缩后的zip文件里包含一级文件目录,不包含二级以下目录,
                 * 直接在这定义String basedir = file.getName() + File.separator;
                 * 下面的compress方法中当判断文件file是目录后不需要加上basedir = basedir + file.getName() + File.separator;
                 * (3)如果想压缩后的zip文件里包含一级文件目录,也包含二级以下目录,即zip文件里的目录结构和原文件一样
                 * 在此定义String basedir = "";
                 * 下面的compress方法中当判断文件file是目录后需要加上basedir = basedir + file.getName() + File.separator;
                 */
                //String basedir = file.getName() + File.separator;
                String basedir = "";
                compress(file, out, basedir);
            }
            out.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    private static void compress(File file, ZipOutputStream out, String basedir) {
        /*
         * 判断是目录还是文件
         */
        if (file.isDirectory()) {
            basedir += file.getName() + File.separator;
            compressDirectory(file, out, basedir);
        } else {
            LOGGER.info("压缩:" + basedir + file.getName());
            compressFile(file, out, basedir);
        }
    }

    /**
     * 压缩一个目录
     */
    private static void compressDirectory(File dir, ZipOutputStream out, String basedir) {
        if (!dir.exists()){
            return;
        }
        //如果文件夹为空,则只需在目的地zip文件中写入一个目录进入点否则空目录不被压缩
         if(files.length==0)
       {
            System.out.println(basedir+"/");
            out.putNextEntry( new ZipEntry(basedir) );
        }
        File[] files = dir.listFiles();
        for (int i = 0; i < files.length; i++) {
            /* 递归 */
            compress(files[i], out, basedir);
        }
    }

    /**
     * 压缩一个文件
     */
    private static void compressFile(File file, ZipOutputStream out, String basedir) {
        if (!file.exists()) {
            return;
        }
        try {
            BufferedInputStream bis = new BufferedInputStream(
                    new FileInputStream(file));
            //创建Zip实体,并添加进压缩包
            ZipEntry entry = new ZipEntry(basedir + file.getName());
            out.putNextEntry(entry);
            //读取待压缩的文件并写进压缩包里
            int count;
            byte data[] = new byte[BUFFER];
            while ((count = bis.read(data, 0, BUFFER)) != -1) {
                out.write(data, 0, count);
            }
            bis.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


//    /**
//     * 解压缩
//     * @param sourceFile 要解压缩的文件的路径
//     * @param destDir 解压缩后的目录路径
//     * @throws Exception
//     */
//    public static void deCompress(String sourceFile,String destDir) throws Exception{
//        //创建需要解压缩的文件对象
//        File file = new File(sourceFile);
//        if (!file.exists()){
//            throw new RuntimeException(sourceFile + "不存在!");
//        }
//        //创建解压缩的文件目录对象
//        File destDiretory  = new File(destDir);
//        if(!destDiretory.exists()){
//            destDiretory.mkdirs();
//        }
//    	/*
//         * 保证文件夹路径最后是"/"或者"\"
//         * charAt()返回指定索引位置的char值
//         */
//        char lastChar = destDir.charAt(destDir.length()-1);
//        if(lastChar!='/'&&lastChar!='\\'){
//            //在最后加上分隔符
//            destDir += File.separator;
//        }
//        unzip(sourceFile, destDir);
//    }
//
//    /**
//     * 解压方法
//     * 需要ant.jar
//     */
//    private static void unzip(String sourceZip,String destDir) throws Exception{
//        try{
//            Project p = new Project();
//            Expand e = new Expand();
//            e.setProject(p);
//            e.setSrc(new File(sourceZip));
//            e.setOverwrite(false);
//            e.setDest(new File(destDir));
//            e.execute();
//        }catch(Exception e){
//            throw e;
//        }
//    }

}
package com.internetware.apistore.controller;

import com.alibaba.fastjson.JSONArray;
import com.internetware.apistore.model.ApiMainInfo;
import com.internetware.apistore.model.ApiPacketParameter;
import com.internetware.apistore.model.ApiVersionInfo;
import com.internetware.apistore.model.JsonResult;
import com.internetware.apistore.service.ApiMainInfoService;
import com.internetware.apistore.service.ApiPacketParameterService;
import com.internetware.apistore.service.ApiVersionInfoService;
import com.internetware.apistore.util.FileUtils;
import com.internetware.apistore.util.ZipUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;

@RestController
@RequestMapping("/api")
public class ApiFileController {

    private final Logger LOGGER = LoggerFactory.getLogger(ApiFileController.class);
    //获取路径
    public String getCurrentPath() throws FileNotFoundException {
        ApplicationHome home = new ApplicationHome(getClass());
        File jarFile = home.getSource();
        return jarFile.toString();

    }

    public String getParentPath() throws FileNotFoundException {
        ApplicationHome home = new ApplicationHome(getClass());
        File jarFile = home.getSource();
        return jarFile.getParent().toString();

    }

    /**
     * 单文件上传
     *
     * @param file
     * @param request
     * @return
     */
    @PostMapping("/uploadFile")
    @ResponseBody
    public String upload(@RequestParam MultipartFile file, HttpServletRequest request) throws FileNotFoundException {
        String fileGuid = request.getParameter("fileGuid");
        String dirType = request.getParameter("dirType");
        String dirName = "";
        String emptyDirFile = "";
        if (dirType != null) {
            if (dirType.equals("daas")) {
                emptyDirFile = "CS";
                dirName = "daas";
            } else if (dirType.equals("CS")) {
                emptyDirFile = "daas";
                dirName = "CS";
            }
        }
        if (!file.isEmpty()) {
            String saveFileName = file.getOriginalFilename();
            File saveFile = new File(getParentPath() + File.separator + "upload" + File.separator + "temp" + File.separator + fileGuid + File.separator + dirName + File.separator + saveFileName);
            File saveFileEmpty = new File(getParentPath() + File.separator + "upload" + File.separator + "temp" + File.separator + fileGuid + File.separator + emptyDirFile + File.separator + saveFileName);
            FileUtils.deleteDir( new File(getParentPath() + File.separator + "upload" + File.separator + "temp" + File.separator + fileGuid + File.separator + dirName));
            if (!saveFile.getParentFile().exists()) {
                saveFile.getParentFile().mkdirs();
            }
            if (!saveFileEmpty.getParentFile().exists()) {
                saveFileEmpty.getParentFile().mkdirs();
            }
            try {
                BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(saveFile));
                out.write(file.getBytes());
                out.flush();
                out.close();
                return JsonResult.success(saveFile.getName() + " 上传成功");
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                return JsonResult.failed("上传失败," + e.getMessage());
            } catch (IOException e) {
                e.printStackTrace();
                return JsonResult.failed("上传失败," + e.getMessage());
            }
        } else {
            return JsonResult.failed("上传失败,因为文件为空.");
        }
    }

    /**
     * 多文件上传
     *
     * @param request
     * @return
     */
    @PostMapping("/uploadFiles")
    @ResponseBody
    @Transactional
    public String uploadFiles(HttpServletRequest request, @RequestParam("file") List<MultipartFile> files) throws IOException {
        String apiVersionId = request.getParameter("apiVersionId");
        String dirType = request.getParameter("dirType");
        String dirName = "";
        if (dirType != null) {
            if (dirType.equals("daas")) {
                dirName = "daas";
            } else if (dirType.equals("CS")) {
                dirName = "CS";
            }
        }
        File savePath = new File(getParentPath() + File.separator + "upload" + File.separator + "temp" + File.separator + apiVersionId + File.separator + dirName);
        if (!savePath.exists()) {
            savePath.mkdirs();
        }
        //List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
        MultipartFile file = null;
        BufferedOutputStream stream = null;
        for (int i = 0; i < files.size(); ++i) {
            file = files.get(i);
            if (!file.isEmpty()) {
                try {
                    byte[] bytes = file.getBytes();
                    File saveFile = new File(savePath, file.getOriginalFilename());
                    stream = new BufferedOutputStream(new FileOutputStream(saveFile));
                    stream.write(bytes);
                    stream.close();
                } catch (Exception e) {
                    if (stream != null) {
                        stream.close();
                        stream = null;
                    }
                    return JsonResult.failed("第 " + i + " 个文件上传有错误" + e.getMessage());

                }
            } else {
                return JsonResult.failed("第 " + i + " 个文件为空");
            }
        }
        return JsonResult.success("所有文件上传成功");
    }

    public static void main(String[] args) throws Exception {
        String srcPathName1 = "E:\\workSpace\\apistore\\apistore-api\\target\\upload\\real\\123";
        String srcPathName2 = "C:/Users/jiahuixi/Desktop/新建文件夹";
        String zipPath1 = "E:\\workSpace\\apistore\\apistore-api\\target\\zipTemp\\123\\ceshi_V1.0.zip";
        String zipPath = "C:/Users/jiahuixi/Desktop/test.zip";
        ZipUtils.compress(zipPath1, srcPathName1);
        ZipUtils.compress(zipPath, srcPathName2);
    }

    //普通java文件下载方法,适用于所有框架
    @GetMapping("/download")
    public String downloadFiles(HttpServletRequest request, HttpServletResponse res) {
        try {

            String apiId = request.getParameter("apiId");
            String apiVerionId = request.getParameter("apiVerionId");
            String apiName = request.getParameter("apiName");
            String apiVersion = request.getParameter("apiVersion");
            String fileName = apiName + "_" + apiVersion;

            outPutJsonAndXml(apiVerionId, apiId);
//            String apiVerionId = "123";
//            String apiName = "ceshi";
//            String apiVersion = "V1.0";
//            String fileName = apiName+"_"+apiVersion;
            String srcPathName = getParentPath() + File.separator + "upload" + File.separator + "real" + File.separator + apiVerionId;
            //String srcPathName2 = "C:/Users/jiahuixi/Desktop/新建文件夹";
            String[] srcPathNames = {srcPathName};
            //String zipPath1 = "C:/Users/jiahuixi/Desktop/test1.zip";
            String zipPath = getParentPath() + File.separator + "zipTemp" + File.separator + apiVerionId + File.separator + fileName + ".zip";
            ZipUtils.compress(zipPath, srcPathNames);
            //方法1:IO流实现下载的功能
            res.setContentType("text/html; charset=UTF-8"); //设置编码字符
            res.setContentType("application/octet-stream"); //设置内容类型为下载类型
            // res.setHeader("Content-disposition", "attachment;filename="+srcPathName1);//设置下载的文件名称
            OutputStream out = res.getOutputStream();   //创建页面返回方式为输出流,会自动弹出下载框
            res.setHeader("Content-disposition", "attachment;filename=" + fileName + ".zip");//设置下载的压缩文件名称
            //将打包后的文件写到客户端,输出的方法同上,使用缓冲流输出
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(zipPath));
            byte[] buff = new byte[bis.available()];
            bis.read(buff);
            bis.close();
            out.write(buff);//输出数据文件
            out.flush();//释放缓存
            out.close();//关闭输出流
            return null;
        } catch (Exception e) {
            e.getStackTrace();
            return null;
        }
    }

}

 

好的,您想了解在 Spring Boot 中如何实现文件上传和下载功能,对吧?那么,我给您简单介绍一下。 首先,在 Spring Boot 中实现文件上传和下载功能,需要用到 Commons FileUpload 和 Commons IO 这两个工具包。您可以在 Maven 中添加以下依赖: ```xml <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.4</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.8.0</version> </dependency> ``` 接下来,我们来看一下文件上传的实现。在 Spring Boot 中,我们可以使用 MultipartFile 类来接收上传的文件。在处理上传请求时,我们需要先判断请求是否为文件上传请求,如果是,则使用 MultipartFile 类来接收上传的文件,并将文件保存到指定的目录中。 ```java @PostMapping("/upload") public String upload(@RequestParam("file") MultipartFile file) throws IOException { if (!file.isEmpty()) { // 获取文件名 String fileName = file.getOriginalFilename(); // 构建文件保存的路径 String filePath = "D:/upload/"; // 创建文件对象 File dest = new File(filePath + fileName); // 判断目标文件所在的目录是否存在,如果不存在则创建目录 if (!dest.getParentFile().exists()) { dest.getParentFile().mkdirs(); } // 保存文件 file.transferTo(dest); return "上传成功!"; } return "上传失败!"; } ``` 接下来,我们来看一下文件下载的实现。在 Spring Boot 中,我们可以使用 ResponseEntity 类来将文件以流的形式返回给前端。 ```java @GetMapping("/download") public ResponseEntity<byte[]> download() throws IOException { // 构建文件对象 File file = new File("D:/upload/test.txt"); // 文件不存在 if (!file.exists()) { return ResponseEntity.notFound().build(); } // 构建文件下载的响应头 HttpHeaders headers = new HttpHeaders(); headers.setContentDispositionFormData("attachment", file.getName()); headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); // 使用 FileUtils 工具类将文件转换成字节数组 byte[] bytes = FileUtils.readFileToByteArray(file); // 返回响应实体对象 return new ResponseEntity<>(bytes, headers, HttpStatus.OK); } ``` 以上就是 Spring Boot 中实现文件上传和下载的基本步骤。需要注意的是,这只是一个简单的示例,实际应用中还需要进行参数校验、异常处理等其他操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值