Course Content‎ > ‎Session 6‎ > ‎

Variable Formatting with PrintWriter

Variables like int, float, double are stored in binary form in a program. In order to read this data into human-readable form, you need to use PrintWriter class. The PrintWriter class is the character-stream class, which provides print and println methods, similar to standard I/O PrintStream class. The print and println methods of the PrintWriter class accept primitive data types and objects. PrintWriter constructor enables automatic flushing i.e. the flush() method is automatically called after the println() method is called.

    //This program writes square of numbers from 0 to 9 in a text file
    public class printWriter
        public static void main (String [] args) throws IOException
            FileWriter output = new FileWriter("filewriter.txt");
            PrintWriter outputPW = new PrintWriter(output);
            int square;
            for(int i=0; i<10; i++)
                square = i * i;
                outputPW.print(square + ", ");

In this example, a file filewriter.txt is created. Using the print method in the PrintWriter object outputPW, integer variable square’s values are displayed in text form in the file.