java常用工具类【如spring 常用工具类,IO流常用工具类等】,持续更新

本文介绍了Java工具类MyUtil,包含从classpath和filesystem读取文件的方法,处理异常,获取系统属性,以及从网络读取和处理图像的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

java常用工具类,持续更新


import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StreamUtils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.Collections;
import java.util.List;

/**
 * 描述:MyUtil 常用工具类
 * @see org.springframework.util.ResourceUtils
 * @see org.springframework.util.StreamUtils
 * @see org.springframework.util.CollectionUtils
 *
 * @see org.apache.commons.io.IOUtils
 * @see org.apache.commons.io.FileUtils
 * @see java.nio.file.Files
 *
 * @see org.apache.commons.collections4.ListUtils
 * @see org.apache.commons.collections4.CollectionUtils
 * @see org.apache.commons.lang3.StringUtils
 *
 * @see javax.imageio.ImageIO
 * @see java.awt.image.BufferedImage
 */
public class MyUtil {
    /**
     * 方法描述:<br/>
     * 从项目根目录【classpath】中读取文件并打印到控制台<br/>
     * 等价于{@link #readFileFromClasspath2(String)}
     * @param fileName
     * @throws IOException
     */
    public static String readFileFromClasspath(String fileName) throws IOException {
        Resource resource = new ClassPathResource(fileName);
        try (InputStream inputStream = resource.getInputStream()) {
            return StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);
        }
    }

    /**
     * 方法描述:
     * 从项目根目录【classpath】中读取文件并打印到控制台
     * @param fileName
     * @throws IOException
     */
    public static String readFileFromClasspath2(String fileName) throws IOException {
        File file = ResourceUtils.getFile("classpath:" + fileName);
        try (InputStream inputStream = Files.newInputStream(file.toPath())) {
            return StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);
        }
    }

    /**
     * 如果不是绝对路径的话,至少要【src/main/】开头
     * @param fileName
     * @return
     * @throws IOException
     */
    public static String readFileFromFilesystem(String fileName) throws IOException {
        Resource resource = new FileSystemResource(fileName);
        try (InputStream inputStream = resource.getInputStream()) {
            return StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);
        }
    }

    /**
     * 获取项目所在位置
     * @return
     */
    public static String getProjectLocation() {
        String userDir = System.getProperty("user.dir");
        return userDir;
    }

    /**
     * 获取项目所在位置
     * @return
     */
    public static void printSystemProperties() {
        System.getProperties().forEach((k, v) -> System.out.println(String.format("%s=%s", k, v)));
    }

    /**
     * 打印当前执行代码所在的方法名称
     * @return
     */
    public static String getCodeExecutePoint() {
        StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
        //第一个方法栈Thread.currentThread().getStackTrace()
        //第二个方法栈是封装的该方法:即:getCurrentClassLocation2()
        //第三个方法栈才是代码执行调用的方法
        StackTraceElement stackTraceElement = stackTraceElements[2];
        return stackTraceElement.toString();
    }

    /**
     * 方法描述:
     * 将异常信息转为字符串
     */
    public static String getStackTrackFromException(Exception e) {
        try (StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw)){
            e.printStackTrace(pw);
            return "\r\n" + sw+ "\r\n";
        } catch (Exception var3) {
            return "getStackTrackFromException error";
        }
    }

    public static String defaultIfBlank(String str,String defaultStr){
        return (str==null||str.equals(""))?defaultStr:str;
    }

    public static String defaultIfNull(String str){
        return str==null?"":str;
    }

    public static List<?> defaultIfNull(List<?> list){
        return list==null? Collections.emptyList():list;
    }

    /**
     *  使用ImageIO从网络上读取图片
     * @param inputUrl url 路径
     * @param outputPath 输出路径:可以时相对路径,也可是绝对路径
     */
    public static void readImageFromUrl(String inputUrl,String outputPath) {
        // 图像 URL
       // String inputUrl = "https://example.com/input.jpg";
       // String outputPath = "output.png";
        try {
            // 从 URL 读取图像
            URL url = new URL(inputUrl);
            BufferedImage inputImage = ImageIO.read(url);

            // 对图像进行处理(这里只是简单地将其复制到另一个 BufferedImage 对象中)
            BufferedImage outputImage = new BufferedImage(inputImage.getWidth(), inputImage.getHeight(), BufferedImage.TYPE_INT_RGB);
            outputImage.createGraphics().drawImage(inputImage, 0, 0, null);

            // 写入图像
            ImageIO.write(outputImage, "png", new File(outputPath));
            System.out.println("写入成功!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        try {
            readImageFromUrl("https://pics5.baidu.com/feed/b151f8198618367ae98737f813adabd9b21ce5f0.jpeg","output.png");
           // System.out.println(getCodeExecutePoint());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值