PrintWriter in Java

Prints formatted representations of objects to a text-output stream.

Constructors

PrintWriter in Java

Methods

Screen Shot 2020-04-05 at 7.52.26 PMScreen Shot 2020-04-05 at 7.52.48 PMScreen Shot 2020-04-05 at 7.53.13 PM

package com.java.io;

import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Locale;

public class PrintWriterExample {

    public static void main(String[] args) {

        FileWriter fw = null;
        PrintWriter pw = null;

        try {
            fw = new FileWriter("/Test/TestFolder/test-file10.txt");
            pw = new PrintWriter(fw);
            // Printing String
            pw.print("Hello");
            pw.println();
            // Printing Boolean
            pw.print(true);
            pw.println();
            // Printing Integer
            pw.print(10); 
            pw.println();
            // Printing Float
            pw.print(1.23 f); 
            pw.println();
            // Format String using format method
              
            pw.format(Locale.US, "This is %s Example using format", "PrintWriter");  
            pw.println();
            // Format String using printf method
              
            pw.printf(Locale.US, "This is %s Example using printf", "PrintWriter");
            pw.flush();
            System.out.println("Data written to File");
        } catch (IOException ioe) {
            ioe.printStackTrace();
        } finally {
            // Closing the streams
            if (fw != null)
                try {
                    fw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            if (pw != null)
                pw.close();
        }
    }

}
Data written to File
Screen Shot 2020-04-05 at 7.29.51 PM

Related Article

Java I/O Basics

Leave a Reply

Your email address will not be published. Required fields are marked *