Java FileWriter Example

The FileWriter class of java.io package makes writing to files in Java as easy as A-B-C. The FileWriter class writes to files as a stream of characters instead of bytes(as in FileOutputStream). Like its input-oriented counterpart FileReader, the FileWriter class is intended for writing “text” based files one character at a time.

Let us look into how FileWriter works in Java.

Constructors

The FileWriter class in Java has five parameterized constructors to allow programmers to manipulate or write to files. Based on the mode of writing, files can be overwritten or appended. Let us take a look at the constructors defined in the FileWriter class.

  • FileWriter(File file) – This constructor accepts a java.io.File object as a parameter and opens the file for writing. By default, this overwrites any previous content of the file.
  • FileWriter(FileDescriptor descriptor) This constructor creates an object of FileWriter which accepts a java.io.FileDescriptor object as a parameter and opens the file referenced by the descriptor object. By default, it overwrites the previous contents.
  • FileWriter(String filePath)This constructor accepts a java.lang.String object as a parameter and opens the file referenced by the path or URI contained in the String and overwrites any existing content in the file.
  • FileWriter(File file, boolean append) This constructor opens accepts a java.io.File and a boolean value as parameter. If the boolean value is true, the existing contents are not overwritten and the new contents are appended
  • FileWriter(String filePath, boolean append) – This constructor opens accepts a java.lang.String and a boolean value as parameter. If the boolean value is true, the existing contents are not overwritten and the new contents are appended.

In both of the last two cases, if the boolean value entered is ‘false’, the contents are overwritten.

If the file is not found or cannot be opened, a FileNotFoundException is thrown.

Methods

The FileWriter class contains methods that allow the programmer to write characters/text to a file. The FileWriter object writes the contents of the file one character at a time.

Let us take a look at the methods we use to write using FileWriter.

  • public void write(int charVal) – This method writes a single character(based on the ASCII value of the input) to the file.
  • public void write(char arr[],int offset,int l) This method writes the characters from the character array from the offset position, for a length ‘l’ of characters.
  • public void write(String str, int offset, int l) This method writes the characters from the String object from the offset position for a length ‘l’ of characters.
  • public void flush()Flushes the current FileWriter object.
  • public void close() – Closes the FileWriter object to prevent any resource leaks.

Example

Let us look at an example of writing to a file with FileWriter class.

Code:

Output:

New Write Complete. File Reads:Hello. I’m writing this new.
Append Complete. File Reads
Hello. I’m writing this new. Append works too

Thats all about java FileWriter example.

Related Posts

  • Set an array to another array in java
    23 April

    Set an Array Equal to Another Array in Java

    Table of ContentsSetting an Array Variable Equal to Another Array VariableSet an Array Equal to Another Array in Java Using the clone() MethodSet an Array Equal to Another Array in Java Using the arraycopy() MethodSet an Array Equal to Another Array in Java Using the copyOf() MethodSet an Array Equal to Another Array in Java […]

  • Java random number between 1 and 100
    07 March

    Generate Random Number Between 1 and 100 in Java

    Table of ContentsUsing Java Util’s Random Class to Generate Random Number Between 1 and 100 in JavaThe nextint() MethodThe ints() MethodUsing Math Class to to Generate Random Number Between 1 and 100 in JavaUsing Apache Commons Library to Generate Random Number Between 1 and 100 in JavaUsing ThreadLocalRandom Library to Generate Random Number Between 1 […]

  • java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList
    22 February

    [Fixed] java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList

    Table of ContentsReason for java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayListFixes for java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayListUse ArrayList’s constructorAssign Arrays.asList() to List reference rather than ArrayList In this post, we will see how to fix java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList. ClassCastException is runtime exception which indicate that code has tried to […]

  • HashMap values cannot be cast to list
    21 February

    [Fixed] java.util.HashMap$Values cannot be cast to class java.util.List

    Table of ContentsWhy HashMap values cannot be cast to list?Fix for java.util.HashMap$Values cannot be cast to class java.util.List In this post, we will see how to fix error java.util.HashMap$Values cannot be cast to class java.util.List. Why HashMap values cannot be cast to list? HashMap values returns java.util.Collection and you can not cast Collection to List […]

  • Format number with Commas in Java
    20 February

    Format Number with Commas in Java

    Table of ContentsHow To Add Commas to Number in Java1. Using DecimalFormat2. Using String’s format() method3. Using System.out.printf4. Using Formatter5. Using NumberFormat In this post, we will see how to format number with commas in java. How To Add Commas to Number in Java There are multiple ways to format number with commas in java. […]

  • Unable to obtain LocalDateTime from TemporalAccessor
    20 February

    [Fixed] Unable to obtain LocalDateTime from TemporalAccessor

    Table of ContentsUnable to obtain LocalDateTime from TemporalAccessor : ReasonUnable to obtain LocalDateTime from TemporalAccessor : FixLocalDate’s parse() method with atStartOfDay()Use LocalDate instead of LocalDateTime In this article, we will see how to fix Unable to obtain LocalDateTime from TemporalAccessor in Java 8. Unable to obtain LocalDateTime from TemporalAccessor : Reason You will generally get […]

Leave a Reply

Your email address will not be published.

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.