Home Java Examples Io Java Write To InputStream
Questions:Ask|Latest

 
 

Share on Google+Share on Google+

Java Write To InputStream

Advertisement
In this tutorial you will learn how to write to InputStream in java. Write to file from InputStream in java you may use the InputStream class of java.io package. This class reads the streams of bytes.

Java Write To InputStream

In this tutorial you will learn how to write to InputStream in java.

Write to file from InputStream in java you may use the InputStream class of java.io package. This class reads the streams of bytes. And to write these streams of bytes FileOutputStream can be used that writes data to a file.

To give the example there a file will be required from where contents can be read and rewritten to the another file. So at first I have created a file and write some text into it.

In the example given below I have created the InputStream 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 :

WriteToInputStream.java

import java.io.*;

class WriteToInputStream
{
public static void main(String args[])
{
InputStream is = null;
OutputStream os = null;
int i= 0;
try
{
File file = new File("writeToInputStream.txt");
is = new FileInputStream("..\\WriteFileFromString\\writeToFileFromString.txt");
os = new FileOutputStream(file);
byte[] data = new byte[1024];
while((i=is.read(data))>0)
{
os.write(data);
}
is.close();
os.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}

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 rewritten 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

Advertisements

If you enjoyed this post then why not add us on Google+? Add us to your Circles



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

Related Tutorials

Ask Questions?    Discuss: Java Write To InputStream  

Post your Comment


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