FileUtils.java 6.73 KB
package cn.com.glsx.wechatbuild.util;

import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;

import javax.validation.constraints.NotBlank;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.UUID;

/**
 * @author huangch
 * @version V1.0
 * @Title: FileUtils
 * @Description:
 * @Company: Didihu.com.cn
 * @Date 2024/3/14 10:33
 */
@Slf4j
@UtilityClass
public class FileUtils {

    /**
     * 根据文件的URL读取文件内容
     * @param fileUrl:
     * @return java.lang.String
     * @author huangch
     * @date 2024/3/14 10:35
     */
    public static String readFile(String fileUrl) throws Exception{
        BufferedReader in = new BufferedReader(new InputStreamReader(new URL(fileUrl).openStream(), "UTF-8"));
        StringBuilder contentBuilder = new StringBuilder();
        String line;
        while ((line = in.readLine()) != null) {
            contentBuilder.append(line);
            contentBuilder.append(System.lineSeparator());
        }
        return contentBuilder.toString().trim();
    }


    /**
     * 获取文件到本地临时目录下
     *
     * @param fileUrl 文件url
     * @return 文件路径,出现异常返回null
     */
    public static String getFileToLocal(@NotBlank String fileUrl, @NotBlank String tempDir, @NotBlank String fileType) {
        try {
            Path directory = Paths.get(tempDir);
            Files.createDirectories(directory);

            URL url = new URL(fileUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);

            if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                log.error("Failed to connect. Response code: {}", connection.getResponseCode());
                return null;
            }

            String fileName = UUID.randomUUID().toString();
            String filePath = tempDir + File.separator + fileName +  "." + fileType;

            try (InputStream inputStream = new BufferedInputStream(connection.getInputStream());
                 OutputStream fileOutputStream = new BufferedOutputStream(Files.newOutputStream(Paths.get(filePath)))) {
                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    fileOutputStream.write(buffer, 0, bytesRead);
                }
            }
            return filePath;
        } catch (Exception e) {
            log.error("Failed to get file from URL: {}", fileUrl, e);
            return null;
        }
    }

    /**
     * 通过文件url获取文件Base64 编码的字符串
     *
     * @param fileUrl
     * @return
     */
    public String getFileAsBase64(String fileUrl) {
        try {
            URL url = new URL(fileUrl);

            try (InputStream inputStream = url.openStream()) {
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int length;

                while ((length = inputStream.read(buffer)) != -1) {
                    byteArrayOutputStream.write(buffer, 0, length);
                }

                byte[] fileBytes = byteArrayOutputStream.toByteArray();
                return Base64.getEncoder().encodeToString(fileBytes);
            }
        } catch (IOException e) {
            log.error("获取文件内容异常,error:{}", e.getMessage(), e);
            return null;
        }
    }

    /**
     * 通过文件url获取文件内容字节数组
     *
     * @param fileUrl
     * @return
     */
    public byte[] getFileAsByteArr(String fileUrl) {
        try {
            URL url = new URL(fileUrl);

            try (InputStream inputStream = url.openStream()) {
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int length;

                while ((length = inputStream.read(buffer)) != -1) {
                    byteArrayOutputStream.write(buffer, 0, length);
                }

                return byteArrayOutputStream.toByteArray();
            }
        } catch (IOException e) {
            log.error("获取文件内容字节数组异常,error:{}", e.getMessage(), e);
            return null;
        }
    }


    /**
     * 创建目录
     *
     * @param dirPath
     * @return 创建目录成功 返回true,否则返回false
     */
    public boolean makeDir(String dirPath) {
        File dir = new File(dirPath);
        if (!dir.exists()) {
            return dir.mkdirs();
        }
        return true;
    }

    /**
     * 移除本地临时文件
     *
     * @param filePath
     * @return
     */
    public boolean removeLocalFile(String filePath) {
        try {
            File tempFile = new File(filePath);
            return tempFile.delete();
        } catch (Exception e) {
            log.error("Failed to remove local file: {}", filePath, e);
            return false;
        }
    }

    public static byte[] fileToByteArray(File file) {
        // 检查文件是否存在
        if (!file.exists()) {
            log.error("File does not exist.");
            return null;
        }

        // 创建一个字节数组输出流
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

        try (FileInputStream fileInputStream = new FileInputStream(file)) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            // 循环读取文件内容到缓冲区,并写入到字节数组输出流
            while ((bytesRead = fileInputStream.read(buffer)) != -1) {
                byteArrayOutputStream.write(buffer, 0, bytesRead);
            }
        } catch (IOException e) {
            log.error("获取文件内容异常,error:{}", e.getMessage(), e);
            return null;
        }

        // 获取字节数组输出流中的字节数组
        return byteArrayOutputStream.toByteArray();
    }

    /**
     * 计算文件大小
     *
     * @param fileData
     * @return
     */
    public String formatFileSize(byte[] fileData) {
        if (fileData == null || fileData.length <= 0) {
            return "0 B";
        }

        Double size = Double.valueOf(fileData.length);
        final String[] units = new String[]{"B", "KB", "MB", "GB", "TB"};
        int index = 0;

        while (size >= 1024 && index < units.length - 1) {
            size /= 1024.0;
            index++;
        }

        return String.format("%.2f %s", size, units[index]);
    }
}