Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read a line in BufferedInputStream?

Tags:

I am writing a code to read Input from user by using BufferedInputStream, But as BufferedInputStream reads the bytes my program only read first byte and prints it. Is there any way I can read/store/print the whole input ( which will Integer ) besides just only reading first byte ?

import java.util.*; import java.io.*; class EnormousInputTest{  public static void main(String[] args)throws IOException {         BufferedInputStream bf = new BufferedInputStream(System.in)   ;     try{             char c = (char)bf.read();          System.out.println(c);     } finally{         bf.close(); }    }    } 

OutPut:

[shadow@localhost codechef]$ java EnormousInputTest 5452 5

like image 751
PankajKushwaha Avatar asked Oct 17 '14 06:10

PankajKushwaha


People also ask

How do I read BufferedInputStream?

read(byte[] b, int off, int len) method reads len bytes from byte-input stream into a byte array, starting at a given offset. This method repeatedly invokes the read() method of the underlying stream.

How do you read InputStream lines?

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.

How does BufferedInputStream work in Java?

The BufferedInputStream maintains an internal buffer of 8192 bytes. During the read operation in BufferedInputStream , a chunk of bytes is read from the disk and stored in the internal buffer. And from the internal buffer bytes are read individually. Hence, the number of communication to the disk is reduced.

What is the difference between FileInputStream and BufferedInputStream?

A BufferedInputStream reads from another InputStream , but a FileInputStream reads from a file1.


1 Answers

A BufferedInputStream is used to read bytes. Reading a line involves reading characters.

You need a way to convert input bytes to characters which is defined by a charset. So you should use a Reader which converts bytes to characters and from which you can read characters. BufferedReader also has a readLine() method which reads a whole line, use that:

BufferedInputStream bf = new BufferedInputStream(System.in)  BufferedReader r = new BufferedReader(         new InputStreamReader(bf, StandardCharsets.UTF_8));  String line = r.readLine(); System.out.println(line); 
like image 179
icza Avatar answered Sep 16 '22 20:09

icza