Home Java Example Java Io FileOutputStream example code



FileOutputStream example code
Posted on: February 19, 2011 at 12:00 AM
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

import java.io.*;

// 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");

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


Related Tags for FileOutputStream example code:


More Tutorials from this section

Ask Questions?    Discuss: FileOutputStream example code  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.