Java Tutorial

Operators

Flow Control

String

Number and Date

Built-in Classes

Array

Class and Object

Inheritance and Polymorphism

Exception Handling

Collections, Generics and Enumerations

Reflection

Input/Output Stream

Annotation

What Is Java Stream? What Is The Input/output Stream?

In Java, the java.io package provides classes for working with input and output (I/O) operations. The package includes classes for reading from and writing to streams. A stream is a sequence of data that can be read from or written to various sources, such as files, network connections, or even other programs.

In this tutorial, we'll cover the basics of using streams in Java, including input/output streams, and file I/O using the FileInputStream and FileOutputStream classes.

1. InputStream and OutputStream

The InputStream and OutputStream are abstract classes that represent the base for all input and output streams in Java. These classes provide methods for reading and writing bytes.

  • InputStream provides methods like read(), available(), and close().
  • OutputStream provides methods like write(), flush(), and close().

2. FileInputStream and FileOutputStream

FileInputStream and FileOutputStream are subclasses of InputStream and OutputStream used for reading from and writing to files.

Example: Reading from a file using FileInputStream

Create a file named "input.txt" with some text in it.

import java.io.FileInputStream;
import java.io.IOException;

public class Main {
    public static void main(String[] args) {
        try {
            FileInputStream fis = new FileInputStream("input.txt");
            int data;

            while ((data = fis.read()) != -1) {
                System.out.print((char) data);
            }

            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

In this example, we create a FileInputStream object to read from the "input.txt" file. We then use the read() method to read each byte of data and print it as a character.

Example: Writing to a file using FileOutputStream

import java.io.FileOutputStream;
import java.io.IOException;

public class Main {
    public static void main(String[] args) {
        try {
            FileOutputStream fos = new FileOutputStream("output.txt");
            String text = "This is a sample text.";

            fos.write(text.getBytes());
            fos.close();

            System.out.println("Text written to the file.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

In this example, we create a FileOutputStream object to write to the "output.txt" file. We then use the write() method to write the bytes of a string to the file.

Note: Since Java 7, you can use try-with-resources to automatically close the streams. This is recommended as it helps prevent resource leaks.

Example of using try-with-resources:

import java.io.FileInputStream;
import java.io.IOException;

public class Main {
    public static void main(String[] args) {
        try (FileInputStream fis = new FileInputStream("input.txt")) {
            int data;

            while ((data = fis.read()) != -1) {
                System.out.print((char) data);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

In this tutorial, we covered the basics of using streams in Java, including input/output streams and file I/O using the FileInputStream and FileOutputStream classes. These classes provide a foundation for working with file I/O in Java, but for more advanced use cases, consider using the java.nio package, which provides better performance and additional features.

  1. Java InputStream and OutputStream Explanation:

    • Overview of Input and Output streams in Java for reading and writing data.
    InputStream inputStream = new FileInputStream("input.txt");
    OutputStream outputStream = new FileOutputStream("output.txt");
    
  2. Working with Java File Streams:

    • Using file streams to read from and write to files in Java.
    FileInputStream fileInputStream = new FileInputStream("input.txt");
    FileOutputStream fileOutputStream = new FileOutputStream("output.txt");
    
  3. Java Byte Stream vs Character Stream:

    • Understanding the distinction between byte and character streams.
    // Byte Stream
    InputStream byteInputStream = new FileInputStream("data.dat");
    OutputStream byteOutputStream = new FileOutputStream("data.dat");
    
    // Character Stream
    Reader charReader = new FileReader("text.txt");
    Writer charWriter = new FileWriter("text.txt");
    
  4. Reading from and Writing to Files in Java:

    • Reading and writing data to files using Java streams.
    try (FileInputStream fis = new FileInputStream("input.txt");
         FileOutputStream fos = new FileOutputStream("output.txt")) {
        // Read from fis and write to fos
    } catch (IOException e) {
        e.printStackTrace();
    }
    
  5. Java FileInputStream and FileOutputStream:

    • Usage of FileInputStream and FileOutputStream for byte-oriented file I/O.
    try (FileInputStream fis = new FileInputStream("input.txt");
         FileOutputStream fos = new FileOutputStream("output.txt")) {
        // Read from fis and write to fos
    } catch (IOException e) {
        e.printStackTrace();
    }
    
  6. BufferedInputStream and BufferedOutputStream in Java:

    • Improving file I/O performance with buffered streams.
    try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream("input.txt"));
         BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("output.txt"))) {
        // Read from bis and write to bos
    } catch (IOException e) {
        e.printStackTrace();
    }
    
  7. Java Data Streams and Serialization:

    • Using DataInputStream and DataOutputStream for primitive data types.
    try (DataOutputStream dos = new DataOutputStream(new FileOutputStream("data.dat"));
         DataInputStream dis = new DataInputStream(new FileInputStream("data.dat"))) {
        dos.writeInt(42);
        int value = dis.readInt();
    } catch (IOException e) {
        e.printStackTrace();
    }
    
  8. PipedInputStream and PipedOutputStream in Java:

    • Communicating between threads using piped streams.
    PipedInputStream pipedInputStream = new PipedInputStream();
    PipedOutputStream pipedOutputStream = new PipedOutputStream();
    pipedInputStream.connect(pipedOutputStream);
    
  9. ObjectInputStream and ObjectOutputStream in Java:

    • Serializing and deserializing objects using object streams.
    try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("object.dat"));
         ObjectInputStream ois = new ObjectInputStream(new FileInputStream("object.dat"))) {
        oos.writeObject(new MyClass());
        MyClass myObject = (MyClass) ois.readObject();
    } catch (IOException | ClassNotFoundException e) {
        e.printStackTrace();
    }
    
  10. Java NIO (New I/O) Streams Overview:

    • Introduction to Java NIO for non-blocking, asynchronous I/O.
    Path filePath = Paths.get("file.txt");
    try (SeekableByteChannel channel = Files.newByteChannel(filePath, StandardOpenOption.READ)) {
        // Read from channel
    } catch (IOException e) {
        e.printStackTrace();
    }
    
  11. Using InputStreamReader and OutputStreamWriter in Java:

    • Converting byte streams to character streams with encoding.
    try (InputStreamReader isr = new InputStreamReader(new FileInputStream("input.txt"), StandardCharsets.UTF_8);
         OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("output.txt"), StandardCharsets.UTF_8)) {
        // Read from isr and write to osw
    } catch (IOException e) {
        e.printStackTrace();
    }
    
  12. Java ByteArrayInputStream and ByteArrayOutputStream:

    • Using in-memory byte arrays for input and output.
    byte[] data = {65, 66, 67};
    try (ByteArrayInputStream bais = new ByteArrayInputStream(data);
         ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
        // Read from bais and write to baos
    } catch (IOException e) {
        e.printStackTrace();
    }
    
  13. Common I/O Stream Exceptions in Java:

    • Handling common exceptions in Java I/O operations.
    try {
        // I/O operations
    } catch (IOException e) {
        e.printStackTrace();
    }