Java Input and Output Stream

In this article we want to learn about Java Input and Output Stream, so first of all let’s talk that what is Input and Output Stream ?

 

 

What is Input and Output Stream ?

So there are different classes in Java that you can use for Input and Output Stream, they provides a way for Java programs to read and write data to external sources. Java IO (Input-Output) package contains several classes and interfaces that allows you to perform input and output operations in Java.

InputStream and OutputStream classes are the two main classes that form the basis of Java Input and Output Stream. InputStream class provides methods for reading data from a source, and  OutputStream class provides methods for writing data to destination.

 

 

For using Java Input and Output Stream, you need to import relevant classes and interfaces from java.io package. this is an example of how to use FileInputStream and FileOutputStream classes to read data from a file and write data to a file:

In the above example we have created an instance of the FileInputStream class for reading data from the file, and name of the file is input.txt. after that we have created an instance of FileOutputStream class to write data to the file, and name of the file is output.txt.

and than we use a while loop to read data from the input stream one byte at a time and write it to the output stream. when we reach the end of the input stream, read() method returns -1, and the loop terminates.

and at the end we close the input and output streams using close() method to free up system resources.

 

 

Learn More

 

Leave a Comment