- 1 year ago
How to run .sh and get return value from Java with file association on Windows
To run a .sh script and get the return value from Java using file association on Windows, you can utilize the Runtime
class in Java. Here's an example code snippet:
javaimport java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class RunShellScript {
public static void main(String[] args) {
String scriptPath = "C:\\path\\to\\script.sh";
String command = "cmd /c start \"" + scriptPath + "\"";
try {
Process process = Runtime.getRuntime().exec(command);
int exitCode = process.waitFor();
// Read the output of the script
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
StringBuilder output = new StringBuilder();
while ((line = reader.readLine()) != null) {
output.append(line).append("\n");
}
// Print the output and exit code
System.out.println("Script Output:\n" + output.toString());
System.out.println("Exit Code: " + exitCode);
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
In this example, we're using the Runtime.getRuntime().exec()
method to execute the script using the cmd /c start
command. The start
command is used to run the script in its associated program defined in the Windows file association.
After running the script, we obtain the exit code of the script using process.waitFor()
. The exit code represents the result of the script execution, where 0
typically indicates success and a non-zero value indicates an error.
To capture the output of the script, we read the input stream of the process using a BufferedReader
and append each line to a StringBuilder
.
Finally, we print the output and exit code to the console.
Make sure to replace "C:\\path\\to\\script.sh"
with the actual path to your .sh script.
Note: The behavior of file association and running scripts may depend on the specific configuration of your system and the associated program. Additionally, this approach relies on the file association being correctly set up for .sh files on your Windows machine.