Java 文件相关


下载文件

//加载文件
        File file = new File(filePath);

        if (!file.exists()) {
            throw new RuntimeException("Can not find file...");
        }

        try (InputStream is = new BufferedInputStream(new FileInputStream(file));
             OutputStream out = new BufferedOutputStream(response.getOutputStream())){
            byte[] buffer = new byte[byteBufferSize];
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(fileName, "UTF-8") + file.getName().substring(file.getName().lastIndexOf(".")));
            response.addHeader("Content-Length", "" + file.length());
            response.setContentType("application/octet-stream");
            int len;
            while ((len = is.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            out.flush();
        } catch (Exception e) {
            log.error("Failed to download file...", e);
            throw new RuntimeException("Failed to download file...");
        }
    }

文件以文件流形式传给前端

try (InputStream in = new FileInputStream(file);
     OutputStream out = response.getOutputStream()) {
    response.reset();
    response.setHeader("Content-disposition", "filename=" + URLEncoder.encode(fileName, "UTF-8") + ".pdf");
    response.setHeader("fileKey", fileKey);
    response.setCharacterEncoding("utf-8");
    response.setContentType("application/pdf");
    byte[] buf = new byte[1024];
    int len = 0;
    while((len = in.read(buf)) != -1){
         out.write(buf, 0, len);
    }
    out.flush();
} catch (Exception e) {
    throw EsrmException.GENERAL_EXCEPTION.of("预览失败");
}

pdf转换图片


    org.apache.pdfbox
    pdfbox
    2.0.20

/**
     * pdf转换图片
     *
     * @param pdfPath      pdf全路径
     * @param imgDirectory 图片目录
     * @param imgName      图片名称
     * @param dpi          图片dpi
     * @param imgType      图片类型
     * @throws IOException
     */
public static List pdfToImage(String pdfPath, String imgDirectory, String imgName, int dpi, String imgType) throws IOException {
    if (StringUtils.isAnyEmpty(pdfPath, imgDirectory, imgName)) {
        throw new IllegalArgumentException();
    }
    if (dpi < 0) {
        dpi = 100;
    }
    if (StringUtils.isEmpty(imgType)) {
        imgType = "png";
    }
    if (!imgDirectory.endsWith("/") && !imgDirectory.endsWith("\\")) {
        imgDirectory += File.separator;
    }

    List imgList = new ArrayList<>();
    //pdf转为byte
    byte[] pdfBytes = Files.readAllBytes(Paths.get(pdfPath));
    PDDocument document = PDDocument.load(pdfBytes);
    //pdf粉刷器
    PDFRenderer renderer = new PDFRenderer(document);
    int pageCount = document.getNumberOfPages();
    for (int i = 0; i < pageCount; i++) {
        BufferedImage bufferedImage = renderer.renderImageWithDPI(i, dpi);
        String imgPath = imgDirectory + File.separator + imgName + "_" + (i + 1) + "." + imgType;
        ImageIO.write(bufferedImage, imgType, new File(imgPath));
        imgList.add(imgPath);
    }
    document.close();
    return imgList;
}

ByteArrayOutputStream & ByteArrayInputStream

此类实例域中有存储数据的缓冲区byte buf[],其中数据被写入到字节数组中, 缓冲区在数据写入时会自动增长,关闭该流无效。关闭此流后它的数据仍然存在,调用方法不会有异常。

reset():重置此字节输出流,废弃此前存储的数据