printwriter-vs-filewriter-class-in-java-with-example

admin

2/27/2025

PrintWriter vs FileWriter in Java

Go Back

PrintWriter vs FileWriter in Java with Examples

Updated: 01/02/2025 by Shubham mishra

Introduction

Writing data to a file is a crucial operation in Java programming. The PrintWriter and FileWriter classes from the java.io package serve this purpose, but they have different functionalities. In this article, we will compare PrintWriter vs. FileWriter in Java, their differences, and when to use each. We will also provide Java code examples for both classes.

PrintWriter vs FileWriter in Java

What is FileWriter in Java?

FileWriter is a class in Java used to write character data to a file. It extends OutputStreamWriter, which in turn extends Writer. It is mainly used for writing raw character data to files.

Features of FileWriter:

  • Writes text to a file using character streams.
  • Provides direct interaction with file output.
  • Less flexible than PrintWriter.

Example 1: Writing to a File using FileWriter

import java.io.*;
import java.util.*;

class FileExample1 {
    public static void main(String args[]) {
        FileWriter fw = null;
        try {
            fw = new FileWriter("D:/Assignments/message.txt");
            Scanner kb = new Scanner(System.in);
            System.out.println("Type a message:");
            String str = kb.nextLine();
            fw.write(str);
        } catch (IOException ex) {
            System.out.println("Error while writing file");
        } finally {
            if (fw != null) {
                try {
                    fw.close();
                    System.out.println("File saved successfully!");
                } catch (IOException ex) {
                    System.out.println("Error while closing file");
                }
            }
        }
    }
}

Example 2: Writing Multiple Data Types Using FileWriter

import java.io.*;
import java.util.*;

class FileExample2 {
    public static void main(String args[]) {
        FileWriter fw = null;
        try {
            fw = new FileWriter("D:/Assignments/myfriends.txt");
            Scanner kb = new Scanner(System.in);
            for (int i = 0; i < 2; i++) {
                System.out.println("Enter name and phone number:");
                String name = kb.next();
                long phone = kb.nextLong();
                fw.write(name + " " + phone + "\r\n");
            }
        } catch (IOException ex) {
            System.out.println("Error while writing file");
        } finally {
            if (fw != null) {
                try {
                    fw.close();
                    System.out.println("File saved successfully!");
                } catch (IOException ex) {
                    System.out.println("Error while closing file");
                }
            }
        }
    }
}

What is PrintWriter in Java?

PrintWriter is a subclass of Writer and provides more advanced methods for writing text data to a file. It supports formatted output and is more convenient for handling multiple data types.

Features of PrintWriter:

  • Provides print() and println() methods.
  • Can handle all primitive data types.
  • Allows formatted output similar to System.out.println().

Example 3: Writing Data to a File using PrintWriter

import java.io.*;
import java.util.*;

class FileExample3 {
    public static void main(String args[]) {
        PrintWriter pw = null;
        try {
            pw = new PrintWriter("D:/Assignments/myfriends.txt");
            Scanner kb = new Scanner(System.in);
            for (int i = 0; i < 2; i++) {
                System.out.println("Enter name and phone number:");
                String name = kb.next();
                long phone = kb.nextLong();
                pw.print(name + " ");
                pw.println(phone);
            }
        } catch (IOException ex) {
            System.out.println("Error while writing file");
        } finally {
            if (pw != null) {
                pw.close();
                System.out.println("File saved successfully!");
            }
        }
    }
}

Key Differences Between FileWriter and PrintWriter

Feature FileWriter PrintWriter
Handles Formatting No Yes
Supports print() & println() No Yes
Can write raw character streams Yes Yes
More user-friendly for formatted output No Yes

When to Use FileWriter vs. PrintWriter

  • Use FileWriter when you need to write raw text or character streams without additional formatting.
  • Use PrintWriter when you need formatted output with additional functionality such as print() and println().

Conclusion

Both FileWriter and PrintWriter are useful for writing data to files in Java. FileWriter is better suited for simple character stream writing, whereas PrintWriter provides advanced text formatting capabilities. If you need more structured output, PrintWriter is the preferred choice.

Table of content