简体   繁体   中英

Java InputStream with a shell script as input to Runtime.getRunTime().exec()

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

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() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM