Skip to main content

Java FileWriter Class

Java FileWriter is a class that belongs to the java.io package. This class is designed to write text to character files in a convenient manner. Before learning about Java FileWriter, let's briefly understand what a character stream is.

What is a character stream?

A character stream, in Java, is a sequence of characters. It can be either input or output. Character streams are able to perform read/write operations from/into a file one character at a time.

Java FileWriter Class

Java FileWriter is an OutputStreamWriter that translates character streams into byte streams. It's mainly used to write character-oriented data to a file.

Constructors of Java FileWriter Class

There are four types of constructors in the FileWriter class:

  • FileWriter(String fileName): Creates a FileWriter object with a given fileName.
  • FileWriter(String fileName, boolean append): Creates a FileWriter object with a given fileName and a boolean indicating whether to append the data written.
  • FileWriter(File file): Creates a FileWriter object with a given File object.
  • FileWriter(File file, boolean append): Creates a FileWriter object with a given File object and a boolean indicating whether to append the data written.

Methods of Java FileWriter Class

Some of the commonly used methods of the FileWriter class are:

  • write(int c): Writes a single character to the current FileWriter stream.
  • write(char[] cbuf): Writes an array of characters to the current FileWriter stream.
  • write(String str): Writes a string to the current FileWriter stream.
  • flush(): Flushes the current FileWriter stream.
  • close(): Closes the current FileWriter stream.

Example of Java FileWriter Class

Let's take a look at an example of how to use FileWriter:

import java.io.FileWriter;

public class MyClass {
public static void main(String[] args) {
try {
FileWriter myWriter = new FileWriter("filename.txt");
myWriter.write("Hello, this is a test.");
myWriter.close();
System.out.println("Successfully wrote to the file.");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}

In the above code:

  • A new FileWriter is created with the name filename.txt.
  • myWriter.write("Hello, this is a test.") is used to write the string "Hello, this is a test." to filename.txt.
  • myWriter.close() is used to close the FileWriter. It's important to close the FileWriter when finished to free up system resources.
  • If an error occurs during this process, the catch block catches the exception and prints an error message.

In conclusion, Java FileWriter is a useful class for writing character data to a file. It provides several constructors and methods that make it user-friendly and flexible for various needs. Remember to always close the FileWriter when you're done using it.