Streams

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:

  1. Reading from a File Using FileInputStream:

    import java.io.*;
    
    public class ByteStreamExample {
        public static void main(String[] args) {
            try {
                FileInputStream inputStream = new FileInputStream("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();
            }
        }
    }
  2. Writing to a File Using FileOutputStream:

    import java.io.*;
    
    public class ByteStreamExample {
        public static void main(String[] args) {
            try {
                FileOutputStream outputStream = new FileOutputStream("output.txt");
                String text = "Hello, Byte Streams!";
                byte[] bytes = text.getBytes();
                outputStream.write(bytes);
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

Character Streams Example:

  1. Reading from a File Using FileReader:

    import java.io.*;
    
    public class CharacterStreamExample {
        public static void main(String[] args) {
            try {
                FileReader reader = new FileReader("input.txt");
                int data;
                while ((data = reader.read()) != -1) {
                    System.out.print((char) data);
                }
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
  2. Writing to a File Using FileWriter:

    import java.io.*;
    
    public class CharacterStreamExample {
        public static void main(String[] args) {
            try {
                FileWriter writer = new FileWriter("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.

Last updated