Logo
Unit 15 – Input and Output Streams in Java

Input and Output Streams in Java

Duration: 5 minutes

Hello, Java programmers!

Today’s topic is Input and Output (I/O) Streams in Java, crucial for reading data from and writing data to different sources like files, network connections, and more. Java I/O streams are used to handle byte or character-based input and output.

There are two main categories of streams:-

Byte Streams (InputStream and OutputStream):

Handle I/O of raw binary data.- **Character Streams (Reader and Writer): ** Handle I/O of character data, automatically handling the encoding and decoding.#### 1. InputStream and OutputStreamThese are used for reading and writing byte-based data, typically used for binary files like images.

Example using FileInputStream and FileOutputStream:

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class ByteStreamExample {
 public static void main(String[] args) {
 try (FileInputStream in = new FileInputStream("input.txt");
 FileOutputStream out = new FileOutputStream("output.txt")) {
 int byteData;
 while ((byteData = in.read()) != -1) {
 out.write(byteData);
 }
 } catch (IOException e) {
 e.printStackTrace();
 }
 }
}

2. Reader and Writer

These are designed for character data, more suitable for text files.Example using FileReader and FileWriter:

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class CharacterStreamExample {
 public static void main(String[] args) {
 try (FileReader reader = new FileReader("input.txt");
 FileWriter writer = new FileWriter("output.txt")) {
 int character;
 while ((character = reader.read()) != -1) {
 writer.write(character);
 }
 } catch (IOException e) {
 e.printStackTrace();
 }
 }
}

Exercise: Implement a Simple Data Stream Operation

Your task is to create a simple program implementing I/O stream operations. Here’s a suggestion:- Use FileInputStream and FileOutputStream to copy a binary file (like an image or a PDF) from one location to another.

  • Use FileReader and FileWriter to read a text file and write its content into a new text file, possibly modifying the content in some way (like converting all text to uppercase).

Conclusion

Great job! You’ve learned about the basic I/O streams in Java, a fundamental concept for handling data in your applications. Understanding these streams is essential for efficient data manipulation in Java.Experiment with these streams to get a practical understanding of their use in different scenarios. This knowledge will be invaluable as you advance in your Java programming journey.Happy coding, and keep exploring the powerful capabilities of Java I/O streams!

You've completed this module!

Continue learning via other JDoodle's professional java Tutorials!

View Modules

Code on the Go with our Mobile App!

Unleash your coding potential anytime, anywhere!

Download Now!