Skip to main content
Published on

FileWriter Class in Java

Share:

Introduction

The FileWriter class in Java allows writing characters to files, making it an essential tool for storing data, logs, configurations, and more. This class acts as a bridge between Java code and the file system, enabling developers to write data in a structured way.

Characteristics of the FileWriter Class

  • Convenience: The FileWriter class makes writing to files a simple and straightforward task.
  • Encoding: It writes characters to files using the system's default encoding or a specified encoding.
  • Extensibility: It can be combined with other classes, such as BufferedWriter, to improve efficiency and add functionality.

Common Methods

In addition to those already mentioned, the FileWriter class has other useful methods:

  • FileWriter().append(): Appends text to the end of the file.
  • FileWriter().flush(): Forces any buffered character output to be written immediately.

Expanded Example

The example presented illustrates how to use the FileWriter class to write a list of countries to a file:

package com.caffeinealgorithm.programaremjava;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class FileWriterClass {
  private File file = new File("File.txt");
  private List<String> countries = new ArrayList<>();
  private FileWriter writeFile;

  public void Run() {
    countries.add("Portugal");
    countries.add("Brazil");
    countries.add("Spain");
    countries.add("France");
    countries.add("Italy");
    countries.add("Australia");
    countries.add("India");

    if (!file.exists()) {
      try {
        file.createNewFile();
        writeFile = new FileWriter(file);

        for (String country : countries)
          writeFile.write(country + '\n');

        writeFile.close();
      }
      catch (IOException exception) {
        System.out.println(exception);
      }
    }
  }
}

Use Cases

  • Application Logs: Record events or errors that occur during program execution.
  • Configurations: Save user preferences or application settings.
  • Data Export: Write data in a specific format to share or migrate between systems.

Conclusion

The FileWriter class is a vital tool for any Java developer who needs to write data to files effectively. Its simplicity and power make the task of file manipulation much more accessible.

Happy coding!