FileWriter in Java


File FileWriter JavaViews 2119

Java FileWriter

How to write to a file in java? – FileWriter in Java is a class that we use to write data in the form of characters to a file. It extends the OutputStream class and writes a stream of characters. The java.io package includes the FileWriter class

FileWriter in Java

Java FileWriter constructors

The Java FileWriter class supports various constructors as listed below:

ConstructorsDescription
FileWriter(File file)Creates a FileWriter object using the specified File
FileWriter(FileDescriptor fd)Creates a FileWriter object using the specified FileDescriptor
FileWriter(String fileName)Creates a FileWriter object using the specified fileName
FileWriter(File file, Boolean append)Creates a FileWriter using the specified file. If the append parameter is true, it appends the values to the file else it overwrites the value
FileWriter(File file, CharSet cs)Creates a FilwWriter object using the specified file and character set
FileWriter(String filename, Boolean append)Creates a FileWriter using the specified filename. If the append parameter is true, it appends the values to the file else it overwrites the value
FileWriter(String filename, CharSet cs)Creates a FileWriter using the specified filename and character set
FileWriter(File file, CharSet cs, boolean append)Creates a FileWriter using the specified file and character set and indicates whether data has to append using the append parameter
FileWriter(String fileName, CharSet cs, boolean append)Creates a FileWriter using the specified filename and character set and appends the values based on the append parameter

FileWriter methods

Below are the various methods of the FileWriter class.

MethodsDescription
Writer append(char c)Appends the specific character to the output stream
Writer append(CharSequence csq)Appends the specific character sequence to the output stream
Writer append(CharSequence csq, int start, int end)Appends the specific character sequence to the output stream specified by the start and end index
void close()Closes the output stream
void flush()Flushes the output stream
String toString()Returns the string representation of the object
void write(char[] c)Writes an array of characters to the output stream
void write(int c)Writes the specified single character to the output stream
void write(String str)Writes the specified string the output stream
void write(char[] c, int off, int len)Writes the specified part of the array of characters based on the specified length and offset
void write(String str, int off, int len)Writes the specified portion of the string based on the offset and length
Writer nullWriter()Returns a new Writer by discarding all the characters

Write a single character and string in a File

In the below example, we write a string and a single character with a line separator to the specified file using the Java FileWriter. Since the append parameter is true, it appends the values every time we execute this code.

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

public class WriteFileDemo {

  public static void main(String[] args) throws IOException {
    FileWriter fw = new FileWriter("OUtputFile.txt", true);
    String text = "FileWriter example";
    char c = 'F';
    
    fw.write(text);
    fw.write("\n");
    fw.write(c);
    
    fw.close();

  }

}

Output File:

FileWriter example
F

Append data in File using Java FileWriter

The append() method of the Java FileWriter appends the specified values to the output file. For this, the append parameter has to be true. In the below example, we append a single character ‘L’, followed by a line separator, then a character sequence “Java” followed by another line separator, and finally a portion of the character sequence with offset as 0 and length 2. Hence it prints only the first 2 characters of the character sequence.

Since the append parameter is true, it retains the old value in the output file which is “FileWriter example F”.

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

public class WriteFileDemo {

  public static void main(String[] args) throws IOException {
    FileWriter fw = new FileWriter("OUtputFile.txt", true);
    CharSequence csq = "Java";
    fw.append("\n");
    fw.append('L');
    fw.append("\n");
    fw.append(csq);
    fw.append("\n");
    fw.append(csq, 0, 2);
    
    fw.close();

  }

}

OutputFile:

FileWriter example
F
L
Java
Ja

Write an array of characters in File

The Java FileWriter class has the write() method to write an array of characters as well. In the below example, we convert the String to a character array using the toCharArray() and then write it to the file using the FileWriter object.

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

public class WriteFileDemo {

  public static void main(String[] args) throws IOException {
    FileWriter fw = new FileWriter("OutputFile.txt", false);
    String value = "Array of characters";
    char[] text = value.toCharArray();
    
    fw.write(text);
    
    fw.close();
    System.out.println("Success");

  }

}

OutputFile.txt

Array of characters

Write a portion of the string in File

We can use the write() method of the FileWriter class to also write only a portion of the specified string by mentioning the offset and length. In this example, we write characters of 5 length starting from position 0. Hence it writes only “Array” text.

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

public class WriteFileDemo {

  public static void main(String[] args) throws IOException {
    FileWriter fw = new FileWriter("OutputFile.txt", false);
    String value = "Array of characters";
        
    fw.write(value, 0, 5);
    
    fw.close();

  }

}

OutputFile.txt

Array

Write a portion of the character array in File

The below example shows how to write a portion of the character array using the FileWriter class. Here we write 10 length characters from the array starting from position 0.

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

public class WriteFileDemo {

  public static void main(String[] args) throws IOException {
    FileWriter fw = new FileWriter("OutputFile.txt", false);
    String value = "Array of characters";
    char[] text = value.toCharArray();
        
    fw.write(text, 0, 10);
    
    fw.close();

  }

}

OutputFile.txt

Array of c

Read and write data using FileReader and FileWriter

Below is an example of how to read from a file using FileReader and write the same content to another file using the FileWriter. Generally, we use a combination of these two classes to read and write data. The InputFile.txt contains the text “Read an input file”. Hence the OutputFile.txt also contains the same after executing this code.

import java.io.*;

public class ReadWriteFile {

  public static void main(String[] args) throws IOException{
    FileWriter fw = new FileWriter("OutputFile.txt");
    FileReader fr = new FileReader("InputFile.txt");
    
    int i;
    //Read until eof
    while((i=fr.read()) != -1)
         //Write to output file
         fw.write(i);
    
    fr.close();
    fw.close();

  }

}

OutputFile.txt

Read an input file

Java FileWriterjava write to file

 

Reference

Translate ยป