0

I am trying to execute a python script that is contained inside .jar. It's works at Eclipse environment but later when try to run from console with java -jar my.jar it failed because it doesn't find the path for file:

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:

In java i am using this:

        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);

I have found answers that recommend that i don't have to use this resourceLoader.getResource("classpath:test.py").getFile(); but resource.getInputStream(). How can i convert this inputstream to a File object to execute it later?

3
  • 1
    Simply create a copy of it (probably a temporary one) and run it just like any other file. Commented Oct 4, 2019 at 9:24
  • worked for me copying file to a tmp folder and execute from there. Thanks @GeorgeZ. Commented Oct 7, 2019 at 9:02
  • I added my comment as answer. Consider accepting it in order to let other users know that the problem has been solved. Commented Oct 7, 2019 at 17:29

1 Answer 1

1

You can not run/open a file that is inside a .jar. In order to run it you will have to copy it, probably in a temporary folder and run it from there. An example where desktop opens an image which is inside .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);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.