Share on Google+Share on Google+

Java Write To File FileOutputStream

In this tutorial you will learn how to write to file using FileOutputStream.

Java Write To File FileOutputStream

In this tutorial you will learn how to write to file using FileOutputStream.

Write to file using FileOutputStream you will have to use the FileOutputStream class of package. This class provides the method write() to write the streams of bytes.

In the example given below I have created an object of FileOutputStream using the constructor FileOutputStream(String name) (this constructor creates the file with the name specified by you into which you want to write your contents) and then write to file using its write() method.

Example :


class WriteTofileFileOutputStream
public static void main(String args[])
File file = null;
FileOutputStream fos = null ;
byte[] byt ={ 65, 67, 95, 97};
String str = "This example demonstrates you how to write to file FileOutputStream";
file = new File("writeTofileFileOutputStream.txt");
fos = new FileOutputStream(file);
for(int i = 0; i< byt.length; i++)

catch(Exception e)
System.out.println("\n Contents are written into new file successfully");

How to Execute this example :

After doing the basic process to execute a java program write simply on command prompt as :

javac to compile the program

And after successfully compilation to run simply type as :

java WriteTofileFileOutputStream

Output :

When you will execute this example a text file will be created on the specified place as the path given by you with containing the text that you are trying to write in that file by java program like as :

Download Source Code



Posted on: January 19, 2012 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: Java Write To File FileOutputStream  

Post your Comment

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