If you create a process with Processbuilder or Runtime in Java, the behavior may not always be the same as the behavior on Linux. If you temporarily create a "bash script (shell script)" and execute it, it may behave as you want.
public void executeCommands() throws IOException {
//Temporary file creation
File tempScript = createTempScript();
try {
//Script execution
ProcessBuilder pb = new ProcessBuilder("bash", tempScript.toString());
//Error output
try (BufferedReader buffer = new BufferedReader(new InputStreamReader(process.getErrorStream()))) {
System.out.println(buffer.lines().collect(Collectors.joining("\n")));
}
//Standard output
try (BufferedReader buffer = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
System.out.println(buffer.lines().collect(Collectors.joining("\n")));
}
Process process = pb.start();
process.waitFor();
} finally {
//Temporary file deletion
tempScript.delete();
}
}
public File createTempScript() throws IOException {
//Temporary file creation
File tempScript = File.createTempFile("script", null);
Writer streamWriter = new OutputStreamWriter(new FileOutputStream(
tempScript));
PrintWriter printWriter = new PrintWriter(streamWriter);
//I will write a script.
printWriter.println("#!/bin/bash");
printWriter.println("cd bin");
printWriter.println("ls");
//End of writing
printWriter.close();
return tempScript;
}
https://stackoverflow.com/questions/26830617/running-bash-commands-in-java
Recommended Posts