Sobes.tech
Junior

What is the difference and what do InputStream, OutputStream, Reader, and Writer have in common?

sobes.tech AI

Answer from AI

General:

  • All are abstract base classes for working with data in Java I/O.
  • They represent data streams.
  • InputStream and Reader are used for reading data, OutputStream and Writer for writing.

Differences:

Characteristic InputStream OutputStream Reader Writer
Data type Bytes (8-bit) Bytes (8-bit) Characters (16-bit Unicode) Characters (16-bit Unicode)
Purpose Reading binary data Writing binary data Reading text data Writing text data
Encoding Not considered Not considered Considered (default or specified) Considered (default or specified)

Usage examples:

// InputStream for reading bytes from a file
try (InputStream is = new FileInputStream("binary.dat")) {
    int byteRead;
    while ((byteRead = is.read()) != -1) {
        // process byteRead
    }
} catch (IOException e) {
    e.printStackTrace();
}
// OutputStream for writing bytes to a file
try (OutputStream os = new FileOutputStream("binary_out.dat")) {
    byte[] data = {1, 2, 3};
    os.write(data);
} catch (IOException e) {
    e.printStackTrace();
}
// Reader for reading characters from a file
try (Reader reader = new FileReader("text.txt")) {
    int charRead;
    while ((charRead = reader.read()) != -1) {
        // process charRead
    }
} catch (IOException e) {
    e.printStackTrace();
}
// Writer for writing characters to a file
try (Writer writer = new FileWriter("text_out.txt")) {
    writer.write("Hello, world!");
} catch (IOException e) {
    e.printStackTrace();
}