Home‎ > ‎Applied Core Java‎ > ‎Basic I/O‎ > ‎

Write Data to a Text File

Problem : How you can write line by line data to a text file?

Solution : 
java.io.FileWriter creates/open an existing file and with help of its write()method you can write charcter by charcter to text file.   java.io.PrintWriter takes a line and convert it into charters and pass charcters to java.io.FileWriter .

Program :

Step 1 - Coding

Create a text file c:/sunilos/WriteFile.java  and copy below contents.

import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.Writer;

 * A program to write in a file.
public class WriteFile {

    public static void main(String[] args) throws Exception{
                   //File writer takes chars and convert into bytes and write to a file 
        FileWriter writer = new FileWriter("c:/sunilos/sunilos-write.txt");
                   // PrintWriter takes lines and convert that into charters and gives to FileWriter 
        PrintWriter printWriter = new PrintWriter(writer);
        for(int i=0;i<5;i++){
        printWriter.println(i +" : Line");

Step 2 - Deployment

  1. Create a folder 'c:\sunilos'. 
  2. Create or copy WriteFile.java  into 'c:\sunilos' folder.
  3. Open your command prompt and go to  'c:\sunilos'
  4. Compile WriteFile.java with help of 
    • javac WriteFile.java command.  Command will create WriteFile.class file in the same folder.
  5. Congratulations!! your Java program is ready to serve.

Step 3 - Testing

  1. Make sure you are on Command Prompt under c:\sunilos directory
  2. Now start your java program from command prompt with help of
    • java -cp . com.sunilos.io.WirteFile command.
  3. Now to check your data open text file.
    • c:\sunilos\sunilos-write.txt




What is FileWriter?

  • FileWriter is meant for writing streams of characters.

What is PrintWriter?

  • PrintWriter print formatted representations of objects to a text-output stream.
  • This class implements all of the print methods found in PrintStream.
  • It does not contain methods for writing raw bytes, for which a program should use unencoded byte streams.

<<Previous | Next>>
Namrata Sisodiya,
Aug 19, 2011, 10:48 PM