4

I have a maven project, in which, I am trying to execute a script (written in R). I put this script file in the source code directory as well. I found this script is not executed at all. However, when I move this script outside the jar file, it does execute ! Can anyone tell me why, and give me some solutions to put the script inside the jar while ensure its execution?

Thanks a lot !

3 Answers 3

6

I would do the following:

  • Get InputStream for the file with ClassLoader.getResourceAsStream()
  • Write this InputStream to tmp dir
  • Execute it with Runtime.getRuntime().execute(..)
Sign up to request clarification or add additional context in comments.

7 Comments

@carlspring yes, i do agree, but it will be better to give a little bit code for step 2. I don't know how to create the temporary file, where the temporary locates, and delete it on exit ? Thanks ~
@EnsomHodder To create use something like this: File.createTempFile("prefix", "suffix")
@EnsomHodder To delete use File.deleteOnExit();
@KonstantinSolomatov so after creating the temp file, I create an outputstream to write the script file into this newly created tmp file, and then call it ?
@KonstantinSolomatov Excuse me, I am trying your method however i cannot manage to it. Firstly, i get the inputstream from the given file name "./src/main/resources/aaa.R" (script to execute) ; secondly, I create a temp file, and from which I create a FileOutputStream to write the script in. However it will throws a NullPointerException when my program tries to read bytes array from the inputstream obtained by getResourcesAsStream. Could you help me survive from it ? I am very grateful for your help !
|
1

File inside jar is no longer a file, So to execute it you first need to extract it somewhere and then execute it from external extracted file path

4 Comments

You mean extract the whole jar file or only the script file to be executed? And could you please tell me how to extract one single file from jar ?
Just extract the required file from jar, see the link for more details from answer
Thanks for your help. after the execution of the script, I have to remove the extracted files. Seems that it's not very clean ~ but most of all, it works
By the way. I don't know where the class ACWrapper comes from? Could you explain it ? thanks
1

You will need to extract the script from the jar file:

jar -xvf my.jar com/foo/my.script.sh

1 Comment

so you mean it's better to execute this command from the Java program, and then execute the second command (extracted file) ? it seems it's quite simple and doesn't not any external library support ~

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.