How to read a line in BufferedInputStream?

PankajKushwaha picture PankajKushwaha · Oct 17, 2014 · Viewed 26.2k times · Source

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

Answer

icza picture icza · Oct 17, 2014

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);