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.

Want to know how to develop your skillset to become a Java Rockstar?

Join our newsletter to start rocking!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

I have read and agree to the terms & conditions

 

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
Inline Feedbacks
View all comments
Back to top button