FileUtil

一、简介

  • 本文主要介绍自己封装的文件工具类

二、代码

package com.zhenai.sweet.qywx.provider.util;

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

import java.io.*;
import java.net.URL;
import java.net.URLConnection;

public class FileUtil {

    private static final Logger logger = LoggerFactory.getLogger(FileUtil.class);

    /**
     * 获取resource目录下的文件路径, 将resource目录下的文件另存到别的地方并绝对路径
     *
     * @param resourceFilePath resource目录下的文件路径,包含文件名 如: /WxWorkLoader.dll
     * @param dirPath          生成的文件的文件目录 d://temp
     * @param fileName         生成的文件的文件夹名称 包含文件类型后缀
     * @return 文件的绝对路径
     */
    public static String getReourceFilePath(String resourceFilePath, String dirPath, String fileName) {

        try (InputStream inputStream = FileUtil.class.getResourceAsStream(resourceFilePath);
             OutputStream outputStream = new FileOutputStream(createFile(dirPath, fileName))) {
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = inputStream.read(buffer, 0, 8192)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        } catch (Exception e) {
            logger.error("获取RESOURCES目录下文件路径失败", e);
        }

        return String.format("%s/%s", dirPath, fileName);
    }


    /**
     * 创建文件
     *
     * @param dirPath  文件路径
     * @param fileName 文件名称 包含文件后缀
     */
    public static File createFile(String dirPath, String fileName) {
        File file;

        File dirFile = new File(dirPath);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }

        file = new File(String.format("%s/%s", dirPath, fileName));
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
        } catch (IOException e) {
            logger.error("创建文件失败", e);
        }
        return file;
    }


    /**
     * 从URL下载文件到本地
     *
     * @param urlString 文件URL
     * @param storePath 存储的相对路径
     * @param filename  文件名称
     * @return 本地的文件路径
     */
    public static String downloadFromUrl(String urlString, String storePath, String filename) {

        try {
            URL url = new URL(urlString);
            URLConnection connection = url.openConnection();
            connection.setConnectTimeout(5 * 1000);

            File storePathDir = new File(storePath);
            if (!storePathDir.exists()) {
                storePathDir.mkdirs();
            }

            String filePath = String.format("%s\\%s", storePath, filename);
            try (InputStream inputStream = connection.getInputStream();
                 OutputStream outputStream = new FileOutputStream(filePath)) {
                byte[] bytes = new byte[1024];
                int len;
                while ((len = inputStream.read(bytes)) != -1) {
                    outputStream.write(bytes, 0, len);
                }
            }

            return filePath;
        } catch (Exception e) {
            logger.error("下载文件失败", e);
        }

        return null;
    }


    public static void main(String[] args) throws Exception {
//        createFile("D://temp//sss", "1.xls");

//        String reourceFilePath = FileUtil.getReourceFilePath("/config/WxWorkLoader.dll", "d://temp", "WxWorkLoader.dll");
//        String reourceFilePath2 = FileUtil.getReourceFilePath("/config/WxWorkHelper.dll", "d://temp", "WxWorkHelper.dll");
//        System.out.println(reourceFilePath);

        String path = downloadFromUrl("https://goss2.cfp.cn/creative/vcg/800/new/VCG41N1203913389.jpg?x-oss-process=image/format,jpg/interlace,1",
                "D:\\temp", "2.png");
        System.out.println(path);
    }
}

 

你可能感兴趣的:(工具类,FileUtil)