Sobes.tech
Junior

Which classes allow converting byte streams to character streams and vice versa?

sobes.tech AI

Answer from AI

Bridge classes (Bridge Streams) are used for this purpose:

  • InputStreamReader: Converts a byte stream (InputStream) into a character stream. The encoding is specified during creation.
  • OutputStreamWriter: Converts a character stream (Writer, e.g., PrintWriter) into a byte stream (OutputStream). It also requires specifying the encoding.

Example of usage:

// Converting a byte stream to a character stream
try (FileInputStream fis = new FileInputStream("input.txt");
     InputStreamReader isr = new InputStreamReader(fis, StandardCharsets.UTF_8)) {
    int data;
    while ((data = isr.read()) != -1) {
        System.out.print((char) data);
    }
} catch (IOException e) {
    e.printStackTrace();
}

// Converting a character stream to a byte stream
try (FileOutputStream fos = new FileOutputStream("output.txt");
     OutputStreamWriter osw = new OutputStreamWriter(fos, StandardCharsets.UTF_8)) {
    osw.write("Sample text for writing");
} catch (IOException e) {
    e.printStackTrace();
}

These classes consider character encoding, which is important when working with text data in different languages.

Which classes allow converting byte streams to… - sobes.tech