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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class Example { public static void main(String[] args) { try { FileInputStream input = new FileInputStream("input.txt"); FileOutputStream output = new FileOutputStream("output.txt"); int data; while ((data = input.read()) != -1) { output.write(data); } input.close(); output.close(); } catch (IOException e) { e.printStackTrace(); } } } |
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
- Java Try Catch Blocks
- Java Checked and Unchecked Exceptions
- Java Exception Propagation
- Java Exception Handling Best Practices