Wednesday, December 11, 2013

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 helloraspberrypi.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".

No comments: