Java Streams   «Prev  Next»

Java write Method - Exercise

Before writing a Java program that reads data from `System.in` and copies each byte read to `System.out` as a byte, a developer should have the following prerequisite Java knowledge:
  1. Understanding Java Input/Output (I/O) Streams
    • Familiarity with byte streams and how Java handles input and output.
    • Knowledge of the InputStream and OutputStream classes in the java.io package.
    • System.in is an instance of InputStream, and System.out is an instance of PrintStream, which is a subclass of OutputStream.
  2. Working with System.in and System.out
    • Understanding how System.in.read() reads one byte at a time and returns it as an int (0-255) or -1 when the end of the stream is reached.
    • Knowing that System.out.write(int b) writes a byte to the standard output stream.
  3. Handling Exceptions (IOException)
    • Since I/O operations can fail, knowing how to handle IOException using try-catch blocks or propagating the exception using throws IOException.
  4. Using Loops for Continuous Reading
    • Understanding while loops to repeatedly read bytes from System.in until the end of the input stream is reached.
    • Recognizing that read() returns -1 when input is EOF (End of File).
  5. Closing Streams Properly (Optional)
    • While System.in and System.out do not need to be closed in most cases, developers should understand the importance of closing streams in general when working with files or sockets.
  6. Basic Command-Line Interaction
    • Knowing how to run a Java program from the command line.
    • Using CTRL+D (on Unix/macOS) or CTRL+Z + Enter (on Windows) to signal EOF when reading from System.in.
  7. Understanding Buffered I/O (Optional for Efficiency)
    • Using BufferedInputStream or BufferedReader for more efficient reading in real-world applications.

Example: Simple Java Program for Byte-by-Byte Copying
import java.io.IOException;

public class CopyBytes {
    public static void main(String[] args) throws IOException {
        int data;
        while ((data = System.in.read()) != -1) { // Read a byte
            System.out.write(data); // Write the byte to output
        }
        System.out.flush(); // Ensure everything is written out
    }
}

How it Works
  • Reads a byte from System.in
  • Writes the same byte to System.out
  • Runs until EOF (-1 is returned by System.in.read())

Additional Knowledge (for Advanced Use Cases)
  • Reading characters instead of bytes (use InputStreamReader and BufferedReader).
  • Handling different encodings (UTF-8 vs. ASCII).
  • Using Scanner for formatted input (if the goal changes from byte-wise copying to processing text input).
Write a program that reads data from System.in and copies each byte read to System.out as a byte.
Paste the source code below and click the Submit Done button when you are ready to submit this exercise.