java 缓冲阅读器和扫描器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5086549/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 09:20:05  来源:igfitidea点击:

buffered reader and scanner

java

提问by dawnoflife

I want to know what's wrong with this. it gives me a constructor error (java.io.InputSream)

我想知道这有什么问题。它给了我一个构造函数错误(java.io.InputSream)

BufferedReader br = new BufferedReader(System.in);
String filename = br.readLine();

回答by corsiKa

A BufferedReader is a decorator that decorates another reader. An InputStream isn't a a reader. You need an InputStreamReader first.

BufferedReader 是装饰另一个阅读器的装饰器。InputStream 不是阅读器。您首先需要一个 InputStreamReader。

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

In response to your comment, here's the javadoc for readline:

为了回应您的评论,这里是 readline 的 javadoc:

readLine

读行

public String readLine()
                throws IOException

    Read a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.

    Returns:
        A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached 
    Throws:
        IOException - If an I/O error occurs

To handle this appropriately you need to either place the method call in a try/catch block or declare that it can be thrown.

要适当地处理这个问题,您需要将方法调用放在 try/catch 块中或声明它可以被抛出。

An example of using a try/catch block:

使用 try/catch 块的示例:

BufferedReader br = new BufferedReader (new InputStreamReader(System.in));

try{
    String filename = br.readLine();
} catch (IOException ioe) {
    System.out.println("IO error");
    System.exit(1);
} 

An example of declaring that the exception may be thrown:

声明可能抛出异常的示例:

void someMethod() throws IOException {
    BufferedReader br = new BufferedReader (new InputStreamReader(System.in));
    String filename = br.readLine();
}

回答by Feisty Mango

For what you are trying to do, I would recommend utilizing the Java.util.Scanner class. Pretty easy for reading input from the console.

对于您想要做的事情,我建议您使用 Java.util.Scanner 类。从控制台读取输入非常容易。

import java.util.Scanner;
public void MyMethod()
{
    Scanner scan = new Scanner(System.in);

    String str = scan.next();
    int intVal = scan.nextInt();
    double dblVal = scan.nextDouble();  
    // you get the idea
}

Here is the documentation link http://download.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html

这是文档链接http://download.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html