【问题标题】:running python script file contained inside a .jar运行包含在 .jar 中的 python 脚本文件
【发布时间】:2019-10-04 08:55:03
【问题描述】:

我正在尝试执行包含在 .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 对象以便稍后执行?

【问题讨论】:

  • 只需创建一个副本(可能是一个临时副本)并像运行任何其他文件一样运行它。
  • 为我工作,将文件复制到 tmp 文件夹并从那里执行。谢谢@GeorgeZ。
  • 我添加了我的评论作为答案。考虑accepting it,以便让其他用户知道问题已解决。

标签: java spring-boot executable


【解决方案1】:

您无法运行/打开位于.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);
}

【讨论】:

    猜你喜欢
    • 2020-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-05
    • 2023-01-08
    • 2011-09-18
    • 2012-02-08
    相关资源
    最近更新 更多