In this section we will read about the OutputStream class of java.io package.
In this section we will read about the OutputStream class of java.io package.In this section we will read about the OutputStream class of java.io package.
OutputStream class is an abstract class provided in the java.io package. OutputStream class is a super class of all the byte stream classes which performs an output of 8-bit bytes. There are several classes which extends this OutputStream class some of these are as follows :
Commonly used Methods of OutputStream
Example :
An example is being given here which demonstrates how to write the output stream data to the specified file. In this example I have tried to read the stream of one file and write these stream to the another file. For this I have created a text file named read.txt which contains some texts and created another text file (if you will not create the write.txt file before execution of the program it will created file the FileOutputStream after successfully execution of the program) named write.txt which has no contents. After completion of this example as a result text of read.txt file will be read by the input stream and write them to the write.txt file. For this I have created an instance of InputStream to read the text and instance of OutputStream to write the text.
Source Code :
/*This example demonstrates that how to write the data output stream to the OutputStream*/ import java.io.InputStream; import java.io.OutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class OutputStreamExample { public static void main(String args[]) { InputStream is = null; OutputStream os = null; try { is = new FileInputStream("read.txt"); os = new FileOutputStream("write.txt"); int c; System.out.println(); System.out.println("Streams of read.txt file has read and has been written to the write.txt file"); System.out.println(); while((c= is.read()) != -1) { os.write(c); } System.out.println(); } catch(IOException e) { System.out.println("IOException caught..!!"); e.printStackTrace(); } finally { if(is != null) { try { is.close(); } catch (IOException ioe) { System.out.println(ioe); } if(os != null) { try { os.close(); } catch(IOException ie) { System.out.println(ie); } } } }// end finally }// end main }// end class
Output :
When you will execute the above example as following then the text of read.txt file will be written to the write.txt file
Ads