To run the terminal from my intelliJ I wrote next code:
public static String runTerminalCommand (String command){
Process proc = null;
try {
proc = Runtime.getRuntime().exec(command);
} catch (IOException e) {
e.printStackTrace();
}
// Read the output
BufferedReader reader =
new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line = "";
try {
while((line = reader.readLine()) != null) {
out.print(line + "\n");
return line;
}
} catch (IOException e) {
e.printStackTrace();
}
try {
proc.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
If there is a way to simplify this :)
I would first look into correctness here; that one line:
return line;
looks suspicious. Or, more precisely: are you sure that your command will always print exactly one line? Because you are returning after reading the first line; and thus omitting any other output.
Besides: you should change your code to use try-with resources instead - your return statement just leaves your readers unclosed. Probably not a problem here because all of that should go away when the process object goes away, but still: bad practice. "Cleanup things" before exiting your methods!
To answer the actual question: after looking into these conceptual things I am pointing out, there isn't much else you could do. Probably use a ProcessBuilder instead of the somehow "outdated" Runtime.exec() call.
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.