Share on Google+Share on Google+

FileOutputStream example code

Learn how to use FileOutputStream of Java to write into a file.

Writing a file using FileOutputStream


Writing a file using FileOutputStream

As we discussed earlier, java has two kinds of streams- Byte & Characters. For reading and writing binary data, byte stream is incorporated. The OutputStream abstract class is used to write data to a file. The FileOutputStream is the subclass of the OutputStream  abstract class. The FileOutputStream  is used to write data to a file.

For writing data like bytes, integers, floats, or other "data" orientated types, we incorporate DataOutputStream while for text we should use PrintStream class.

Given below example will give you a clear idea how to use FileOutputStream :



// Example of FileOutputStream
public class FileOutStreamDemo {
public static void main(String[] args) {
FileOutputStream out; // declare a file output object
PrintStream p; // declare a print stream object

try {
// Create a new file output stream
// connected to "DevFile.txt"
out = new FileOutputStream("DevFile.txt");

// Connect print stream to the output stream
p = new PrintStream(out);

p.println("The text shown here will write to a file after run");

System.out.println("The Text is written to DevFile.txt");

} catch (Exception e) {
System.err.println("Error writing to file");


Output :

The following message will appear on command prompt :

 The Text is written to DevFile.txt   

The Content of the text file:

Download Source Code



Posted on: February 19, 2011 If you enjoyed this post then why not add us on Google+? Add us to your Circles

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.

Discuss: FileOutputStream example code  

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
July 9, 2012

Good and very simple example to understand how to write into file