kamboj
kamboj

Reputation: 411

running python script file contained inside a .jar

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?

Upvotes: 0

Views: 227

Answers (1)

George Z.
George Z.

Reputation: 6808

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

Upvotes: 1

Related Questions