Wednesday, December 11, 2013

Example of using PrintWriter

This example show a how to use PrintWriter to print to System.out and file. PrintWriter prints formatted representations of objects to a text-output stream. We will use last example of "ProcessBuilder to create operating system processes" to get input from.

package java_processbuilder;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @web java-buddy.blogspot.com
 */
public class Java_ProcessBuilder {

    public static void main(String[] args) {

        // Example to run "dir" in Windows
        String[] command = {"cmd", "/c", "dir"};
        StringBuilder cmdReturn = new StringBuilder();
        try {
            //print to System.out
            PrintWriter printWriter_out = new PrintWriter(System.out, true);
            
            //print to file, text.txt
            File file = new File("test.txt");
            file.createNewFile();
            try (PrintWriter printWriter_file = new PrintWriter(new FileWriter(file))) {
                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());
                printWriter_out.println(cmdReturn.toString());
                printWriter_file.println(cmdReturn.toString());
            }

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

No comments:

Post a Comment