Write Text into File

In this section, you will learn how to write text into a file.

Write Text into File

In this section, you will learn how to write text into a file.

Write Text into File

Write Text into File

     

In this example we are writing text into file.In this example we are initialize string to write into file. We are creating file in which we are writing string by use of write() method.

We need  java.io.*  package import first. The create   a .txt file with name "write.txt". We are using FileWriter class to read file for modification. BufferedWriter class is used for buffering the file which will store into an object of  Writer class .Then we are using write() method to write text into file. At last close output file using close() method.

The code of the program is given below:

import java.io.*;

public class WriteTextFileExample{
  public static void main(String[] args)throws IOException{
  Writer output = null;
  String text = "Rajesh Kumar";
  File file = new File("write.txt");
  output = new BufferedWriter(new FileWriter(file));
  output.write(text);
  output.close();
  System.out.println("Your file has been written");  
  }
}
 

The output of the program is given below:

C:\convert\rajesh\completed>javac WriteTextFileExample.java
C:\convert\rajesh\completed>java WriteTextFileExample
Your file has been written

Download this example.