Java 如何读取 BufferedInputStream 中的一行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26419538/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to read a line in BufferedInputStream?
提问by PankajKushwaha
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 ?
我正在编写一个代码来使用 BufferedInputStream 从用户读取输入,但是当 BufferedInputStream 读取字节时,我的程序只读取第一个字节并打印它。除了只读取第一个字节之外,有什么方法可以读取/存储/打印整个输入(将是 Integer )?
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
[shadow@localhost codechef]$ java EnormousInputTest 5452 5
采纳答案by icza
A BufferedInputStream
is used to read bytes. Reading a line involves reading characters.
ABufferedInputStream
用于读取字节。阅读一行包括阅读字符。
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:
您需要一种将输入字节转换为由charset定义的字符的方法。因此,您应该使用 aReader
将字节转换为字符并且您可以从中读取字符。BufferedReader
还有一个readLine()
读取整行的方法,使用它:
BufferedInputStream bf = new BufferedInputStream(System.in)
BufferedReader r = new BufferedReader(
new InputStreamReader(bf, StandardCharsets.UTF_8));
String line = r.readLine();
System.out.println(line);
回答by sam_eera
You can run this inside a while loop.
您可以在 while 循环中运行它。
Try below code
试试下面的代码
BufferedInputStream bf = new BufferedInputStream(System.in) ;
try{
int i;
while((i = bf.read()) != -1) {
char c = (char) i;
System.out.println(c);
}
}
finally{
bf.close();
}
}
But keep in mind this solution is inefficient than using BufferedReader
since InputStream.read()
make a system call for each character read
但请记住,此解决方案比使用效率低,BufferedReader
因为InputStream.read()
对每个读取的字符进行系统调用