Writing to File in Java

In this tutorial, you will learn how to write character in a file and how to write text in a file in java language.

Writing to File in Java

In this tutorial, you will learn how to write character in a file and how to write text in a file in java language.

Writing to File in Java


Writing to File in Java

Writing any character or text in Java file is possible through using some defined classes such as FileWriter or BufferedWriter in Java programming. The programmers choose the class as per the need as particular class functions particular tasks.

In Java, FileWriter and BufferedWriter are used for writing Character files and Text Files respectively while another class OutputStreamWrite class is used to handle raw byte file.

Class FileWriter

Class FileWriter accedes from the OutputStreamWriter class, used for writing streams of characters. The FileWriter is a class used for writing character files. The FileWriter class has several constructors that can be used according to required objects.

Syntax of class FileWriter:

FileWriter(File file)

This is the simplest example of the class used for writing character file.

BufferedWriter

The BufferWriter class in Java is a character streams class used to write text to a character-output stream. Using this class you can write single character, text, strings, and arrays directly into a file.

Syntex of Class BufferedWriter:

newBufferedWriter(Path, Charset, OpenOption...)

This is the simplest example of the class used for writing text files.

Example:

import java.io.*;
class FileWrite 
{
 public static void main(String args[])
  {
  try{
  // Create file 
  FileWriter fstream = new FileWriter("out.txt");
  BufferedWriter out = new BufferedWriter(fstream);
  out.write("Hello Java");
  //Close the output stream
  out.close();
  }catch (Exception e){//Catch exception if any
  System.err.println("Error: " + e.getMessage());
  }
  }
}