Write to a file in Java - Sample Program

By: Dorris  

This sample Java program demonstrates how to write to a file in Java. For this, the following two classes FileWriter and BufferedWriter are used. This program can be used to write to any text file using a Java Program.

FileWriter

The FileWriter is a class used for writing character files. The constructors of this class assume that the default character encoding and the default byte-buffer size are acceptable. To specify these values yourself, construct an OutputStreamWriter on a FileOutputStream.

BufferedWriter

The BufferWriter class is used to write text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings.

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());
    }
  }
}



Archived Comments

1. http://www.roseindia.net/java/beginners/java-write-to-file.shtml
View Tutorial          By: Bankelal at 2013-02-05 17:04:00

2. You know what will be usefull if we can use this in a java command line console to like when compli
View Tutorial          By: mechkid at 2012-12-03 14:54:41

3. google.com
View Tutorial          By: amit at 2012-08-05 18:43:19

4. import java.io.File;
import java.util.Scanner;

public class FileExists {

View Tutorial          By: sa at 2012-08-02 07:09:30

5. I have an array.
How can I write, delete, update it on file??
any one help me??thank a

View Tutorial          By: tung at 2011-04-10 22:10:19


Most Viewed Articles (in Java )

Latest Articles (in Java)

Comment on this tutorial