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.

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

WriteToFileFromInputStream.java

import java.io.*;

class WriteToFileFromInputStream
{
public static void main (String args[])
{
File file = null;
FileInputStream fis = null;
FileOutputStream fos = null;
int i = 0;
try
{
fis = new FileInputStream("existingFile.txt");
file = new File("writeToFileFromInputStream.txt");
fos = new FileOutputStream(file);
byte[] data = new byte[1024];
while((i=fis.read(data))>0)
{
fos.write(data);
}
fis.close();
fos.flush();
fos.close();
}
catch(Exception e)
{
System.out.println(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 WriteToFileFromInputStream.java to compile the program

And after successfully compilation to run simply type as :

java WriteToFileFromInputStream.java

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