Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Java Example Java Io Write to a file

Related Tutorials


 
 

Share on Google+Share on Google+

Write to a file

Advertisement
As we have read about the BufferedOutputStream class that store the data in an internal buffer and lets you write characters to a stream. Lets see an example that writes the text "Hello Java" to the existed file.

Write to a file

     

As we have read about  the BufferedOutputStream class that store the data in an internal buffer and lets you write characters to a stream. Lets see an example that writes the text "Hello Java" to the existed file.

The given example uses the BufferedOutputstream class that writes the bytes to the output stream. The output stream is a file "Filterfile.txt" in which the data is written in form of a byte. The getBytes( ) method of the String class returns the bytes from the string.

 

import java.io.*; 

class WriteFilter
{
  public static void main(String args[])
  {
  String str="Hello Java";
  try 
  {
  FileOutputStream fos = new FileOutputStream("Filterfile.txt");
  BufferedOutputStream bos = new BufferedOutputStream(fos);
  
  // Now write to the buffered stream.
 bos.write(str.getBytes());
   bos.flush();
  System.out.print("the data has been written")
  
  catch (Exception e
  {
  System.err.println("Error writing to a file: " + e);
  }
  }
}

Output of the Program:

C:\nisha>javac WriteFilter.java

C:\nisha>java WriteFilter
the data has been written
C:\nisha>

Download this Program

Advertisement

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: December 17, 2008

Related Tutorials

Discuss: Write to a file   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0
DMCA.com