Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

buffered reader and scanner

Tags:

java

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

BufferedReader br = new BufferedReader(System.in);
String filename = br.readLine();
like image 494
dawnoflife Avatar asked Dec 28 '22 01:12

dawnoflife


2 Answers

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

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

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

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.

An example of using a try/catch block:

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();
}
like image 110
corsiKa Avatar answered Jan 09 '23 17:01

corsiKa


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

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

like image 33
Matthew Cox Avatar answered Jan 09 '23 19:01

Matthew Cox