Share on Google+Share on Google+

Java Write To File From FileInputStream

In this tutorial you will learn how to write to file from FileInputStream.

Java Write To File From FileInputStream

In this tutorial you will learn how to write to file from FileInputStream.

Write to file from FileInputStream in java you may use the FileInputStream class of package. This class takes input bytes from a file or can say it reads the streams of bytes. And to write these streams of bytes you may use FileOutputStream that writes data to a file.

To do so at first you will required an existing file content of which you want to write into another file. So at first I have created a text file and write some text into it.

In the example given below I have created the FileInputStream object and passed the existing file name into its instance to read the contents, and created a new file using File into which the contents of an existing file will be rewritten to it. Then passed the object of this file in FileOutputStream instance to write the contents that are read from the existing file.

Example :


class WriteToFileFromInputStream
public static void main (String args[])
File file = null;
FileInputStream fis = null;
FileOutputStream fos = null;
int i = 0;
fis = new FileInputStream("existingFile.txt");
file = new File("writeToFileFromInputStream.txt");
fos = new FileOutputStream(file);
byte[] data = new byte[1024];
catch(Exception e)
System.out.println("\n New file is created 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 :


Output :

When you will execute this example, contents of an existing file will be first read by FileInputStream and a new file will be created and then read contents will be written to it using the FileOutputStream :

1. An existing file that contains some text.

2. A newly created file into which an existing file contents will be rewritten.

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 From FileInputStream  

Post your Comment

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