在jar包中读取文件时报错

选择新建远程调试配置 picture 0

设置远程调试参数 picture 1

IDEA启动后提示

SH

Connected to the target VM, address: 'localhost:5005', transport: 'socket'

通过命令行启动jar包时设置调试参数

SH

java -Xdebug -Xrunjdwp:transport=dt_socket,address=5005,server=y,suspend=y -jar cosimcloud-dataspaces-1.0.jar
Listening for transport dt_socket at address: 5005

如下所示,通过该工具类可以在idea或jar包环境中读取资源文件

java

public class PathUtil {
    public static InputStream asStream(String path) throws FileNotFoundException {
        Path res = Paths.get(path).toAbsolutePath();
        if (Files.exists(res)) {
            return new FileInputStream(res.toFile());
        }

        URL resource = PathUtil.class.getClassLoader().getResource(path);
        if (resource != null) {
            // 将URL转换为文件对象
            return PathUtil.class.getClassLoader().getResourceAsStream(path);
        }

        resource = PathUtil.class.getClass().getResource(path);
        if (resource != null) {
            return PathUtil.class.getClass().getResourceAsStream(path);
        }
        throw new FileNotFoundException(path);
    }
}

相关内容