问题
项目A代码调用到Resouces下的文件a.sh,打包成Jar包后,项目B调用对应方法时,出现报错,找不到a.sh文件路径,原来的代码可能是:
URL resource = getClass().getClassLoader().getResource("a.sh");
String path = resource.getPath();
System.out.println(path);
这样项目B是读取不到文件的。
解决方案
通过stream流获取文件,创建临时文件,记得处理异常以及临时文件执行结束后删除。
// 使用 ClassLoader 获取资源文件的 InputStream
InputStream inputStream = this.class.getClassLoader().getResourceAsStream("a.sh");
if (inputStream == null) {
throw new IOException("The script file was not found in the resources directory.");
}
// 创建临时文件
File tempScript = Files.createTempFile("tempScript", ".sh").toFile();
tempScript.setExecutable(true);
// 将资源文件内容写入临时文件
try (FileOutputStream outputStream = new FileOutputStream(tempScript)) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
}