JAVA操作文件相关

1、下载压缩包

package 
import io.swagger.annotations.ApiParam;

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

/**
 * @ClassName Test
 * @Author 123
 * @Version 1.0
 * 介绍:
 */
public class Test {

    /**
     * 下载压缩包
     * @param response
     * @param request
     * @param id
     */
    public void downloadReel(HttpServletResponse response, HttpServletRequest request, String id) {
        try {
            String filePath = "D:\\file\\";
            ArchiveTreeEntity reel = FileService.findById(id);
            String fileName = reel.getName() + ".zip";

            List<ArchiveFileEntity> list = FileService.getFileList(id);

            ZipOutputStream zipOut = new ZipOutputStream(response.getOutputStream());
            // 浏览器处理乱码问题
            String userAgent = request.getHeader("User-Agent");

            // 文件名外的双引号处理firefox的空格截断问题
            response.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", fileName));
            response.setContentType("application/x-msdownload");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));

            String path = filePath + reel.getName();
            File outFile = new File(path);
            for (int i = 0; i < list.size(); i++) {
                ArchiveFileEntity entity = list.get(i);
                if (!outFile.exists()) {
                    outFile.mkdirs();
                }
                String url = filePath + entity.getAddress();
                //将文件存储至一个临时文件中
                uploadFileTemp(url, path, entity.getName());
            }
            File file = new File(path);// 要被压缩的文件夹
            if (file.isDirectory()) {
                File[] files = file.listFiles();
                for (File fileSec : files) {
                    recursionZip(zipOut, fileSec, file.getName() + File.separator);
                }
            }
            zipOut.closeEntry();
            zipOut.close();
            //删除临时文件夹
            deleteDir(outFile);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }


    /**
     * 打包压缩文件
     *
     * @param zipOut  压缩文件流
     * @param file    文件
     * @param baseDir 分隔符
     * @throws Exception
     */
    private void recursionZip(ZipOutputStream zipOut, File file, String baseDir) throws Exception {
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (File fileSec : files) {
                recursionZip(zipOut, fileSec, baseDir + file.getName() + File.separator);
            }
        } else {
            byte[] buf = new byte[1024];
            InputStream input = new FileInputStream(file);
            zipOut.putNextEntry(new ZipEntry(baseDir + file.getName()));
            int len;
            while ((len = input.read(buf)) != -1) {
                zipOut.write(buf, 0, len);
            }
            input.close();
        }
    }

    /**
     * 将文件下载至一个临时文件中
     *
     * @param urlPath 文件地址
     * @param targetDirectory 临时文件地址
     * @param fileName 文件名
     * @throws Exception
     */
    public void uploadFileTemp(String urlPath, String targetDirectory, String fileName) throws Exception {
        InputStream inputStream = new FileInputStream(urlPath);
        byte[] buff = new byte[1024 * 10];
        OutputStream out = new FileOutputStream(new File(targetDirectory, fileName));
        int lenth = -1;
        while ((lenth = inputStream.read(buff)) != -1) {
            out.write(buff);
            out.flush();
        }
        // 关闭资源
        out.close();
        inputStream.close();
    }


    /**
     * 删除临时文件夹
     *
     * @param dir
     * @return
     */
    private 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();
    }
}

2、图片转base64

package 


import org.apache.commons.codec.binary.Base64;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * @ClassName Test
 * @Author 123
 * @Version 1.0
 * 介绍:
 */
public class Test {
    
    private String file2Base64(File file) {
        if (file == null) {
            return null;
        }
        String base64 = null;
        FileInputStream fin = null;
        try {
            fin = new FileInputStream(file);
            byte[] buff = new byte[fin.available()];
            fin.read(buff);
            base64 = Base64.encodeBase64String(buff);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fin != null) {
                try {
                    fin.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return base64;
    }

}

3、PDF操作

package 

import com.itextpdf.text.Document;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import org.apache.pdfbox.pdmodel.PDDocument;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

/**
 * @ClassName PdfUtil
 * @Author 123
 * @Version 1.0
 * 介绍:Pdf 操作工具类
 */
public class PdfUtil {

    /**
     * 通过PDFbox获取文章总页数
     *
     * @param filePath:文件路径
     * @return
     */
    public static int getNumberOfPages(String filePath) {
        PDDocument pdDocument = null;
        try {
            pdDocument = PDDocument.load(new File(filePath));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                pdDocument.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        int pages = pdDocument.getNumberOfPages();
        return pages;
    }

    /**
     * 合并pdf
     *
     * @param files   所有文件地址
     * @param newfile 新文件的地址
     * @return
     */
    public static boolean mergePdfFiles(List<String> files, String newfile) {
        if (files.get(0) == null) {
            return false;
        }
        boolean retValue = false;
        Document document = null;
        try {
            Rectangle pageSize = new PdfReader(files.get(0)).getPageSize(1);
            if (pageSize == null) {
                return false;
            }
            document = new Document();
            PdfCopy copy = new PdfCopy(document, new FileOutputStream(newfile));
            document.open();
            for (int i = 0; i < files.size(); i++) {
                PdfReader reader = new PdfReader(files.get(i));
                int n = reader.getNumberOfPages();
                for (int j = 1; j <= n; j++) {
                    document.newPage();
                    PdfImportedPage page = copy.getImportedPage(reader, j);
                    copy.addPage(page);
                }
            }
            retValue = true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            document.close();
        }
        return retValue;
    }
}

4、文件下载

package com.resafety.transfer.archive.controller;


import com.resafety.transfer.archive.entity.ArchiveFileEntity;
import io.swagger.annotations.ApiParam;

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

/**
 * @ClassName Test
 * @Author 123
 * @Version 1.0
 * 介绍:
 */
public class Test {
    public void download(String fid, HttpServletResponse response, HttpServletRequest request) {
        try {
            ArchiveFileEntity fileEntity = FileService.findById(fid);
            File file = new File("D:\\" + fileEntity.getAddress());
            String suffix = fileEntity.getSuffix();
            String filename = fileEntity.getName();
            FileInputStream fis = new FileInputStream(file);
            response.reset();
            // 设置response的Header
            String contentType = "";
            if (suffix.equals(".doc") || suffix.equals(".docx")) {
                contentType = "application/msword";
            } else if (suffix.equals(".xls") || suffix.equals(".xlsx")) {
                contentType = "application/vnd.ms-excel";
            } else if (suffix.equals(".ppt") || suffix.equals(".pptx")) {
                contentType = "application/vnd.ms-powerpoint";
            } else if (suffix.equals(".pdf")) {
                contentType = "application/pdf";
            } else {
                contentType = "application/ms-download";
            }
            response.setContentType(contentType);

            response.setHeader("Content-Disposition", "" +
                    "inline;filename=\"" + new String(filename.getBytes("gbk"), "iso8859-1") + "\"");
            response.setHeader("Access-Control-Allow-Origin", "*");
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            byte[] buffer = bos.toByteArray();
            response.getOutputStream().write(buffer);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

5、多文件上传

	//可以定义实体类接受:private List<MultipartFile> files;
    public RestResult<Integer> save(HttpServletRequest request) {
        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartHttpServletRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entry : fileMap.entrySet()) {
            MultipartFile multipartFile = entry.getValue();
        }
     }
  //JS
  	   var formData = new FormData();
  	   //fileArr文件数组
        for (var i = 0; i < fileArr.length; i++) {
            formData.append("files", fileArr[i]);
        }
        //【千万别这样写】一次性加入后端映射不到formData.append("files", fileArr)
        $.ajax({
            type: "post",
            url: "http://127.0.0.1:9090/",
            data: formData,
            processData: false,// 固定格式
            contentType: false, // 固定格式
            dataType: "json",
            success: function (data) {
            }
        });

总结:对日常操作文件进行总结、如有疑问可以进行评论

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值