Ticker

6/recent/ticker-posts

Run system command and read output using Java

The exercise run system command with StringBuilder(), and read the output with InputStream.

import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
*
* @org java-buddy.blogspot.com
* @web picturedmagazine.blogspot.com
*/
public class df {

public static void main(String[] args) {

// Example to run "dir" in Windows
String[] command = {"df", "-h", "/"};
StringBuilder cmdReturn = new StringBuilder();
try {
ProcessBuilder processBuilder = new ProcessBuilder(command);
Process process = processBuilder.start();

try (InputStream inputStream = process.getInputStream()) {
int c;
while ((c = inputStream.read()) != -1) {
cmdReturn.append((char) c);
}
}
System.out.println(cmdReturn.toString());

} catch (IOException ex) {
Logger.getLogger(df.class.getName())
.log(Level.SEVERE, null, ex);
}

}

}

Run system command and read output using Java

The code from Java-Buddy: ProcessBuilder to create operating system processes

Related: Read Pi's system temperature in Java, using ProcessBuilder with command of "vcgencmd measure_temp".

إرسال تعليق

0 تعليقات