Java FileWriter Example
In this example, we will discuss the Java FileWriter class and how to use it to write streams of characters. This is the class used in Java in order to write to file.
Whether or not a file is available or may be created depends upon the underlying platform. Some platforms, in particular, allow a file to be opened for writing by only one FileWriter (or other file-writing object) at a time. In such situations, the constructors in this class will fail if the file involved is already open.
FileWriter
extends OutputStreamWriter
, which is a bridge from character streams to byte streams: Characters written to it are encoded into bytes using a specified charset. The charset that it uses may be specified by name or may be given explicitly, or the platform’s default charset may be accepted.
The FileWriter
class exists since JDK1.1.
1. The structure of the Java FileWriter
Constructor:
FileWriter(File file)
Constructs aFileWriter
object given aFile
object.FileWriter(File file, boolean append)
Constructs aFileWriter
object given aFile
object. If the second argument istrue
, then bytes will be written to the end of the file rather than the beginning.FileWriter(FileDescriptor fd)
Constructs aFileWriter
object associated with a file descriptor.FileWriter(String fileName)
Constructs aFileWriter
object given a file name.FileWriter(String fileName, boolean append)
Constructs aFileWriter
object given a file name with a boolean indicating whether or not to append the data written.
2. Overwriting vs. Appending the File
The constructor FileWriter(File file, boolean append) has a boolean flag as a second parameter and work as follows:
- Overwrite
If append is set to false then it wil create a FileWriter that will overwrite any content that is currently in that file
- Append
If append is set to true then it wil create a FileWriter that appends to an existing file.
3. The FileWriter in Java
To show a basic usage of FileWriter
I created this class called SimpleFileWriterExample
:
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | package com.javacodegeeks.examples; import java.io.File; import java.io.FileWriter; import java.io.IOException; public class SimpleFileWriterExample { public static void main(String[] args) { String name = "John Doe" ; int age = 44 ; double temp = 26.9 ; FileWriter fw; try { fw = new FileWriter( new File( "mytextfile.txt" )); fw.write(String.format( "My name is %s." ,name)); fw.write(System.lineSeparator()); //new line fw.write(String.format( "I am %d years old." ,age)); fw.write(System.lineSeparator()); //new line fw.write(String.format( "Today's temperature is %.2f." ,temp)); fw.write(System.lineSeparator()); //new line fw.close(); } catch (IOException ex) { ex.printStackTrace(); } System.out.println( "Done" ); } } |
What I just did was creating an instance of FileWriter
, passing a File
as a parameter, and then I started writing on it, using System.lineSeparator()
to create new lines into the file. In the end of this, I closed the FileWriter
instance, using the close()
method, inherited from the OutputStreamWriter
.
If you open the file, you will see this:
1 2 3 | My name is John Doe. I am 44 years old. Today's temperature is 26.90. |
4. Difference between flush and close
- flush() writes the content of the buffer to the destination and makes the buffer empty for further data to store but it does not closes the stream permanently. That means you can still write some more data to the stream.
- close() closes the stream permanently. If you want to write some data further, then you have to reopen the stream again and append the data with the existing ones.
5. A better usage of FileWriter
To show a more practical usage of the FileWriter
in Java, I created a simple Logger, which can be used to log data into a text file. So, create a class called Logger
into the mylogger
package, and put this code into it:
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | package com.javacodegeeks.examples.mylogger; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Date; public class Logger { private File logFile; public Logger() { } public Logger(String fileName) { logFile = new File(fileName); } public Logger(File f) { logFile = f; } public void log(String s) { try { FileWriter fw = new FileWriter( this .logFile, true ); String date = new Date().toString(); fw.write(date+ " : " +s); fw.write(System.lineSeparator()); fw.close(); } catch (IOException ex) { System.err.println( "Couldn't log this: " +s); } } } |
This class creates a Logger
object which you can use to log into a file by calling the log()
method. To test this, create a new class, called Main
, with this source code:
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 | package com.javacodegeeks.examples.mylogger; import java.io.File; public class Main { public static void main(String[] args) { Logger log1 = new Logger( "file1.txt" ); File f = new File( "file2.txt" ); Logger log2 = new Logger(f); log1.log( "This is written in the first file" ); log2.log( "This is written in the second file" ); log1.log( "This is appended to the first file" ); log2.log( "This is appended to the second file" ); } } |
Here I just tested the two different constructors and logged two messages into two different files. The output in them is this:
1 2 | Tue Aug 26 16:21:06 PDT 2014 : This is written in the first file Tue Aug 26 16:21:06 PDT 2014 : This is appended to the first file |
And this:
1 2 | Tue Aug 26 16:21:06 PDT 2014 : This is written in the second file Tue Aug 26 16:21:06 PDT 2014 : This is appended to the second file |
6. More about FileWriter in Java
FileWriter’s performance can be improved with BufferedWriter. BufferedWriter writes text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings. BufferedWriter
extends Writer
, which is an abstract class for writing to character streams. The only methods that a subclass must implement arewrite(char[], int, int), flush()
, and close()
. Most subclasses, however, will override some of the methods defined here in order to provide higher efficiency, additional functionality, or both.
All of the constructors of FileWriter
throw an IOException
if the named file exists but is a directory rather than a regular file, or it does not exist but cannot be created, or it cannot be opened for any other reason.
7. Download the source code
You can download the full source code of this example here : Java FileWriter Example
Last updated on Apr. 29th, 2020