In Java, I/O (Input/Output) streams are used for reading and writing data from and to different sources, such as files, network connections, or in-memory buffers. Java provides two main types of I/O streams: byte streams and character streams. Byte streams are used for handling binary data, while character streams are used for handling text data. Below are examples of how to use both byte and character streams in Java.
Byte Streams Example:
Reading from a File Using FileInputStream:
importjava.io.*;publicclassByteStreamExample {publicstaticvoidmain(String[] args) {try {FileInputStream inputStream =newFileInputStream("input.txt");int data;while ((data =inputStream.read()) !=-1) {System.out.print((char) data); // Convert to char for text }inputStream.close(); } catch (IOException e) {e.printStackTrace(); } }}
importjava.io.*;publicclassCharacterStreamExample {publicstaticvoidmain(String[] args) {try {FileWriter writer =newFileWriter("output.txt");String text ="Hello, Character Streams!";writer.write(text);writer.close(); } catch (IOException e) {e.printStackTrace(); } }}
Remember to handle exceptions properly and close streams in a finally block or use try-with-resources (available since Java 7) to ensure proper resource management.