Java FileWriter tutorial

Java FileWriter tutorial shows how to use FileWriter class to write text to files in Java.

Java FileWriter

FileWriter is a Java convenience class for writing text data to files. FileWriter extends OutputStreamWriter and creates the FileOutputStream.

Java FileWriter constructors

These are FileWriter constructors:

Java FileWriter write to file

With FileInputStream and FileOutputStream we create streams for reading and writing to a File. When the file is not found, FileNotFoundException is thrown. File is a representation of a file or directory in Java.

JavaFileWriterEx.java
package com.zetcode;

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

public class JavaFileWriterEx {

    public static void main(String[] args) throws IOException {
        
        try (FileWriter writer = new FileWriter("src/resources/myfile.txt")) {
            writer.write("Today is a sunny day");
        }
    }
}

The example writes text data to a file with FileWriter.

try (FileWriter writer = new FileWriter("src/resources/myfile.txt")) {

The FileWriter constructor takes a string as a parameter; it is the file name to which we write. We use try-with-resources construct to clean resources after we have finished writing.

writer.write("Today is a sunny day");

The FileWriter's write() method writes text to the file.

Java FileWriter append to file

With FileWriter it is possible to append text to a file. The typical usage for appending is logging.

JavaFileWritterAppend.java
package com.zetcode;

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

public class JavaFileWritterAppend {

    public static void main(String[] args) throws IOException {
        
        String fileName = "src/resources/myfile.txt";
        File myfile = new File(fileName);
        
        try (FileWriter writer = new FileWriter(myfile, true)) {
            writer.write("Tomorrow will be cloudy.");
        }        
    }
}

The code example appends text to file.

try (FileWriter writer = new FileWriter(myfile, true)) {

The second parameter of FileWriter tells that we will append to the file.

FileWriter with BufferedWriter

FileWriter's performance can be improved with BufferedWriter. BufferedWriter writes text to a character-output stream, buffering characters to improve the performance of writing single characters, arrays, and strings. The buffer size may be specified, or the default size may be accepted; the default is large enough for most purposes.

JavaFileWriterBuffered.java
package com.zetcode;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

public class JavaFileWriterBuffered {

    public static void main(String[] args) throws MalformedURLException, IOException {

        String text = readText();

        String fileName = "src/resources/wikipedia_home_page.txt";

        try (FileWriter writer = new FileWriter(fileName);
                BufferedWriter bufWriter = new BufferedWriter(writer)) {
            bufWriter.write(text);
        }
    }

    public static String readText() throws MalformedURLException, IOException {

        StringBuilder sb;

        URL url = new URL("https://www.wikipedia.org");
        try (BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()))) {
            String line;
            
            sb = new StringBuilder();
            
            while ((line = br.readLine()) != null) {
                
                sb.append(line);
                sb.append(System.lineSeparator());
            }
        }
        
        return sb.toString();
    }
}

In the example, we read Wikipedia's home page (its HTML code) and write it to a file. The home page is large enough to consider buffering.

try (FileWriter writer = new FileWriter(fileName);
        BufferedWriter bufWriter = new BufferedWriter(writer)) {
    bufWriter.write(text);
}

The FileWriter is passed to the BufferedWriter as a parameter. Then we call the BufferedWriter's write() method to write the text.

try (BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()))) {

The reading operation is buffered as well with the BufferedReader class.

Specifying encoding

FileWriter uses the default encoding and does not allow us to explicitly specify the encoding. If we have to set the encoding, we can use OutputStreamWriter and FileOutputStream.

JavaFileOutputStreamEx.java
package com.zetcode;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;

public class JavaFileOutputStreamEx {

    public static void main(String[] args) throws FileNotFoundException, IOException {
        
        String fileName = "src/resources/myfile.txt";
        
        try (OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(fileName), 
                StandardCharsets.UTF_8)) {
            osw.write("Сегодня был прекрасный день.");
        }
    }
}

The example writes text to a file with OutputStreamWriter. The second parameter is the charset to be used.

In this tutorial, we have presented the Java FileWriter class. You might also be interested in the related tutorials: Java FileOutputStream tutorial, Java file time, Java append to file, Reading text files in Java, Reading and writing ICO images in Java, Java Swing tutorial, Java tutorial, Displaying image in Java.