我正在尝试执行.jar中包含的python脚本。它可以在Eclipse环境下工作,但是稍后尝试使用java -jar my.jar从控制台运行时失败了,因为它找不到文件的路径:
Caused by: java.io.FileNotFoundException: class path resource [test.py] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:
在Java中,我正在使用此:
File file = resourceLoader.getResource("classpath:test.py").getFile();
map.put("file", file.getPath());
CommandLine commandLine = new CommandLine("python.exe");
commandLine.addArgument("${file}");
commandLine.addArgument("-e");
commandLine.addArgument("env");
commandLine.addArgument("-i");
commandLine.addArgument("'" + id + "'");
commandLine.setSubstitutionMap(map);
我已经找到建议我不必使用此resourceLoader.getResource("classpath:test.py").getFile();
而是resource.getInputStream()
的答案。我如何将该输入流转换为File对象以在以后执行?
您无法运行/打开.jar
内部的文件。为了运行它,您必须将其复制(可能在一个临时文件夹中)并从那里运行。桌面打开.jar
内部图像的示例:
public static void main(String[] args) throws IOException {
String pathOfImageInsideJar = Test.class.getResource("/test/example/image.jpg").getFile();
File imageInsideJar = new File(pathOfImageInsideJar);
File tempExport = File.createTempFile("tempimage", ".jpg");
tempExport.deleteOnExit();
Files.copy(imageInsideJar.toPath(), tempExport.toPath(), StandardCopyOption.REPLACE_EXISTING);
Desktop.getDesktop().open(tempExport);
}