FileUtils.java 4.25 KB
package com.bs.reception.utils;

import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;

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

    public static Long fileSize(String filePath) {
        long fileSize = 0;
        try {
            fileSize = Files.size(Paths.get(filePath));
            return fileSize;
        } catch (IOException e) {
            log.error("读取文件大小出现异常 filePath:{}", filePath);
            throw new RuntimeException("读取文件大小出现异常 filePath:" + filePath);
        }
    }

    /**
     * 根据文件的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();
    }

    public String replaceAliOssDomain(String url, String useInternal) {
        if (!StringUtils.hasLength(useInternal) || "0".equals(useInternal)) {
            return url;
        }
        String replace = StringUtils.replace(url, "glsk-oss.oss-cn-shenzhen.aliyuncs.com", "glsk-oss.oss-cn-shenzhen-internal.aliyuncs.com");
        log.debug("内网oss域名已处理:old:{},new:{}", url, replace);
        return replace;
    }

    /**
     * 获取文件到本地临时目录下
     *
     * @param fileUrl 文件url
     * @return 文件路径,出现异常返回null
     */
    public String getFileToLocal(String fileUrl, String tempDir) {
        try {
            if (!makeDir(tempDir)) {
                log.error("Failed to create directory: {}", tempDir);
                return null;
            }

            URL url = new URL(fileUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                log.error("Failed to connect. Response code: {}", connection.getResponseCode());
                return null;
            }

            String[] splitTemp = fileUrl.split("/");
            String fileName = splitTemp[splitTemp.length - 1];
            String filePath = tempDir + System.currentTimeMillis() + fileName;

            // 创建文件输出流,用于将数据写入本地临时目录
            FileOutputStream fileOutputStream = new FileOutputStream(filePath);

            byte[] buffer = new byte[4096];
            int bytesRead;

            InputStream inputStream = connection.getInputStream();
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                fileOutputStream.write(buffer, 0, bytesRead);
            }

            // 关闭流
            fileOutputStream.close();
            inputStream.close();
            return filePath;
        } catch (IOException e) {
            log.error("Failed to get file from URL: {}", fileUrl, 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;
        }
    }



}