缓冲的阅读器和扫描仪

时间:2011-02-23 02:59:59

标签: java

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

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

2 个答案:

答案 0 :(得分:8)

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

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

在回复你的评论时,这里是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

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

使用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);
} 

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

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

答案 1 :(得分:1)

对于您要执行的操作,我建议使用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
}

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