做门图网站,网页访问自动跳转中,潍坊专业做网站,邯郸匿豪网络科技有限公司问题
项目A代码调用到Resouces下的文件a.sh#xff0c;打包成Jar包后#xff0c;项目B调用对应方法时#xff0c;出现报错#xff0c;找不到a.sh文件路径#xff0c;原来的代码可能是#xff1a;
URL resource getClass().getClassLoader().getResource(a.sh打包成Jar包后项目B调用对应方法时出现报错找不到a.sh文件路径原来的代码可能是
URL resource getClass().getClassLoader().getResource(a.sh);
String path resource.getPath();
System.out.println(path);
这样项目B是读取不到文件的。
解决方案
通过stream流获取文件创建临时文件记得处理异常以及临时文件执行结束后删除。 // 使用 ClassLoader 获取资源文件的 InputStreamInputStream 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);}}