ProcessBuilder At the current site, there was a request to hit Shell from within Java, so as a result of investigating, it was introduced in this article ** ProcessBuilder * It seems that you should use something called *. I have diverted the linked code, but when I actually use it, I will dynamically change the call destination of the process ... So, I wrote a memo completely.
CallOutsideProcess.java
/**
Call as many arguments as you like at the caller.
Ex) execute(new String[]{"ping","111,222,33,4"});
*/
public class CallOutsideProcess {
public void execute(String args[]) {
try {
Process process = new ProcessBuilder(args).start();
InputStream is = process.getInputStream();
/*Depending on the output of the character string etc. on the process execution side
If the character codes do not match, the characters will be garbled when receiving.*/
InputStreamReader isr = new InputStreamReader(is, "Shift-JIS");
// InputStreamReader isr = new InputStreamReader(is, "UTF-8");
BufferedReader reader = new BufferedReader(isr);
StringBuilder builder = new StringBuilder();
int c;
while ((c = reader.read()) != -1) {
builder.append((char) c);
}
//Storage of character strings output to the console
text = builder.toString();
//Exit code storage(0:Normal termination 1:Abnormal termination)
int ret = process.waitFor();
System.out.println(text);
System.out.println(ret);
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
It was a content that I was likely to use in the future, so let's remember ... ~~ (... I wrote it so that I can remember it even if I forget it) ~~
Recommended Posts