PrintWriter in Java

The PrintWriter class in Java is the most enhanced writer to write character data to the file. The main advantage of PrintWriter over FileWriter & BufferedWriter is we can write any type of primitive data directly to a file.

PrintWriter Constructors

PrintWriter class in Java provides different constructors for different use cases and requirements. Here are some primary constructors of the PrintWriter class –

PrintWriter(File file)

public PrintWriter(@NotNull  File file )
 throws FileNotFoundException

This constructor takes a File object as an argument and creates a PrintWriter that writes data at the specified file.

PrintWriter(String fileName)

public PrintWriter(  @NotNull  String fileName )
 throws FileNotFoundException

If the constructor takes a file name as an argument and creates a PrintWriter that writes data to the file with the given file name.

PrintWriter(OutputStream out)

public PrintWriter(   @NotNull  OutputStream out )

In scenarios where data needs to be written to an OutputStream then this constructor can be used. It allows us to utilize various output streams like FileOutputStream or BiteArrayOutputStream.

PrintWriter(Writer out)

public PrintWriter(    @NotNull  Writer out )

For cases that involve character-based output then this constructor is suitable.

Note- PrintWriter can communicate directly with files and also can communicate via some Writer object.

PrintWriter Methods

write()

public void write(int c )
public void write(String s )
public void write(char[] ch)

print() and println()


import java.io.FileNotFoundException;
import java.io.PrintWriter;

public class PrintWriterExample {
    public static void main(String[] args) throws FileNotFoundException {
        PrintWriter pw = new PrintWriter("FileWriterExample.txt");
        pw.write(45);
        pw.println(true);
        pw.println("Java");
        pw.flush();
        pw.close();
    }
}

Similar Java Tutorials

Leave a Comment