Curriculum
Course: Learn Java Programming
Login

Curriculum

Learn Java Programming

Video lesson

Writing to the File Using FileWriter Class in Java

In this lesson, you will learn.

  • Background: I/O Stream Classes
  • Writing to a File
  • Example

 

Background

The java.io package provides a rich set of classes to perform input and output (I/O) operations. Java categorizes these stream classes into two main types based on the data they handle.

 

FileClasses

  • Byte streams read and write 8-bit bytes and are primarily used for handling binary data like images, audio files, and compiled code.
  • The FileInputStream class reads bytes from a file, and the FileOutputStream class writes bytes to a file. The BufferedInputStream provides buffering for an input stream, improving reading efficiency, and the BufferedOutputStream provides buffering for an output stream, improving writing efficiency.
  • Character streams are used for reading and writing Unicode characters (16-bit), used mainly for handling text data.
  • The FileReader class reads text data from a file using a read() method, and the FileWriter class writes characters to a File using a write() method.
  • The BufferedReader provides buffering for an input character stream, improving reading efficiency by reading lines of text. It also provides the readLine() method. The BufferedWriter provides buffering for an output character stream, improving writing efficiency. It also provides a newLine() method for writing platform-specific line separators.

In this lesson, you will learn Character stream classes, i.e, FileWriter class to write data to a file.

 

Writing to a File Using FileWriter Class

 

1. Using the FileWriter Class

  • A convenience class for writing character files.
  • It inherits from OutputStreamWriter and assumes the default character encoding of the system.
  • Provides write() methods to write single characters, character arrays, or strings to a file.
  • Usage: Suitable for simple text file writing when you don’t need to specify encoding or require buffering.

 

FileWriter Constructors

The four commonly used constructors are shown here:

1. FileWriter(String fileName): Creates a FileWriter object given the name of the file. It will overwrite the content of the file if it exists.

2. FileWriter(String fileName, boolean append): Creates a FileWriter object given a file name with an option to append. If append is true, then data will be written to the end of the file rather than the beginning.

3. FileWriter(File file): Creates a FileWriter object given a File object. This constructor will also overwrite the existing file.

4. FileWriter(File file, boolean append): Similar to the second constructor but uses a File object. It allows appending if the boolean append is set to true.

 

Example 1: Using FileWriter(String fileName)

package filewriting;

import java.io.FileWriter;
import java.io.IOException;

public class FileWriterExample1 {
    public static void main(String[] args) {
        try {
            FileWriter writer = new FileWriter("src/filewriting/example1.txt");
            writer.write("Hello, this is text written to a file.");
            writer.write("\nNandini");
            writer.write("\nRam");
            System.out.println("The file writing operation completed!");
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Output

The file writing operation completed!

 

This constructor overwrites example.txt if it exists or creates a new file if it doesn’t.

 

Example 2: Using FileWriter(String fileName, boolean append)

package filewriting;

import java.io.FileWriter;
import java.io.IOException;

public class FileWriterExample2 {
    public static void main(String[] args) {
        try {
        	FileWriter writer = new FileWriter("src/filewriting/example2.txt",true);
            writer.write("nAppending this line to the file.");
            writer.write("nNandini");
            writer.write("nRam");
            
            System.out.println("The file writing operation completed!");
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Output

The file writing operation completed!

 

This code appends text to the existing example2.txt file. If the file does not exist, it creates a new file.

 

Example 3: Using FileWriter(File file)

package filewriting;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class FileWriterExample3 {
    public static void main(String[] args) {
        File file = new File("src/filewriting/example3.txt");
        try {
            FileWriter writer = new FileWriter(file);
            writer.write("Writing to a file using File object.");
            System.out.println("The file writing operation completed!");
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

This approach uses a File object to specify the file path, which is useful when the file object is already available from previous operations.

 


End of the lesson….enjoy learning

 

 

Student Ratings and Reviews

 

5.0
5.0 out of 5 stars (based on 1 review)
Excellent100%
Very good0%
Average0%
Poor0%
Terrible0%

 

 

25/05/2025

The notes are concise, well-summarized, and perfect for quick revision before exams or interviews and youtube tutorials are also helpful . watching tutorial and revision here make java easy .

Nikhilyadav07

 

 

Submit a Review