Difference between InputStream and OutputStream in Java

Simply an InputStream is used to read from a source, and an OutputStream is used to write to a destination.

Difference between InputStream and OutputStream

The goal of the streams is to provide an interface to read or write data, regardless of whether the source or destination is a file, the console, an HTTP request or a remote computer. Remains the same:

  • Read from an InputStream.
  • Write to an OutputStream.

So the In or Out is seen from the view of the program: Input to the program, output from the program.
java-mcq-multiple-choice-questions-and-answersJava MCQ – Multiple Choice Questions and Answers – OOPsThis collection of Java Multiple Choice Questions and Answers (MCQs): Quizzes & Practice Tests with Answer focuses on “Java OOPs”.   1. Which of the…Read More


InputStream example

First of all: there are better ways to read a text file. This example is only intended to illustrate how the InputStream class works:

public static String readFromInputStream(String file) throws IOException 
    try(InputStream is = new FileInputStream(file)) 
        byte[] data = new byte[1024];
        StringBuilder sb = new StringBuilder();

        int bytes =;
        while (bytes > 0)
            sb.append(new String(Arrays.copyOfRange(data, 0, bytes), "UTF-8"));
            bytes =;
        return sb.toString();

Since a file is being read, the FileInputStream class is used. Reading works as follows:

  • The method read(byte[] buffer) takes a byte array and writes the bytes of the stream into the array until either the array is full or no more bytes can be read.
  • The return value of “” returns the number of bytes that have been read.
  • The byte array is now used (in this case converted into a string), but only as much as was read into the buffer.
  • If there are no more bytes to read, the stream must be closed. In this case we save ourselves the closing because the try with resources syntax is used, which has been part of Java since Java 7. The InputStream is instantiated in the round brackets of the try statement, whereby the stream is automatically closed at the end of the block.


Java 8 Stream TutorialJava 8 Stream TutorialOne of the big innovations of Java 8 is the new Streams API (Package A stream in the sense of this API is simply…Read More mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *