Home Java Examples Io Java Write To File FileOutputStream
Questions:Ask|Latest


 
 

Share on Google+Share on Google+

Java Write To File FileOutputStream

Advertisement
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 java.io 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 :

WriteTofileFileOutputStream.java

import java.io.*;

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";
try
{
file = new File("writeTofileFileOutputStream.txt");
fos = new FileOutputStream(file);
for(int i = 0; i< byt.length; i++)
{
fos.write(byt[i]); 
}

fos.write(str.getBytes());
fos.close();
}
catch(Exception e)
{
System.out.println(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 WriteTofileFileOutputStream.java 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

Advertisement

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: January 19, 2012

Ask Questions?    Discuss: Java Write To File FileOutputStream  

Post your Comment


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