1

I am running a java program using a Jar file. Inside this packaged jar file I have my shell script. I understand that the best way to access the file would be through getResourcesAsStream because I can't access it via regular directory structures. So this is what I'm using:

    InputStream input = this.getClass().getResourceAsStream("/script/sample_script.sh");

However, The only way I know how to execute this is if I go through the script line by line using a loop and bufferReader. I Statements like "If" or "While" loops get me an error. Is there a way to input the stream to achieve the desired results.

Here is my current code:

InputStream input = this.getClass().getResourceAsStream("/script/sample_script.sh");
BufferedReader brCmd = new BufferedReader(new InputStreamReader(input));
String cmd;
while ((cmd = brCmd.readLine()) != null){
     proc = Runtime.getRuntime().exec(cmd);
     proc.waitFor();
}

I've tried concatenating the whole file line by line to a string and using that but it doesn't seem to work. How can I get to make my script file run using inputStream? Any help would be appreciated

1
  • You need to close the process's input, output, and error streams, after consuming the two latter, before calling waitFor(). Commented Aug 10, 2020 at 10:04

1 Answer 1

1

You could read the script file through InputStream and write it to a temp file under the system temp directory, and execute this file in following way:Runtime.getRuntime.exec("/bin/sh " + tempFilePath);

About reason to rewrite the script file to another temp file, you said you are executing your program by run the jar file directly, thus the script file is packed into the jar file and java won't unpack the jar file to the file system. To let the script file be accessible to cmd.exe, we need to rewrite the script file manually.

By the way, you could get the system temp directory path from system properties, or using apache common.io: FileUtils.getTempDirectory().

Sign up to request clarification or add additional context in comments.

1 Comment

Looks like I'll have to create a temp file after all. Thanks :)

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.