InputStream

Read line of chars from console with InputStream

In this example we shall show you how to read a line of chars from console with an InputStream. This abstract class is the superclass of all classes representing an input stream of bytes. Applications that need to define a subclass of InputStream must always provide a method that returns the next byte of input. To read a line of chars from console with an InputStream one should perform the following steps:

  • Use System.in to get the standard InputStream.
  • Create a new BufferedReader with a new InputStreamReader with the specified InputStream.
  • Use readLine() API method of BufferedReader to read a line of text.
  • Close the BufferedReader, using the close() API method,

as described in the code snippet below.

package com.javacodegeeks.snippets.core;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class ReadLineOfCharsFromConsoleWithInputStream {
	
	public static void main(String[] args) {
		
		InputStream is = null;
		BufferedReader br = null;
		
		try {
			
			is = System.in;
			br = new BufferedReader(new InputStreamReader(is));
			
			String line = null;
			
			while ((line = br.readLine()) != null) {
				if (line.equalsIgnoreCase("quit")) {
					break;
				}
				System.out.println("Line entered : " + line);
			}
			
		}
		catch (IOException ioe) {
			System.out.println("Exception while reading input " + ioe);
		}
		finally {
			// close the streams using close method
			try {
				if (br != null) {
					br.close();
				}
			}
			catch (IOException ioe) {
				System.out.println("Error while closing stream: " + ioe);
			}

		}
		
	}

}

 
This was an example of how to read a line of chars from console with an InputStream in Java.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button