Scanner vs. BufferedReader

前端 未结 12 1759
死守一世寂寞
死守一世寂寞 2020-11-22 02:17

As far I know, the two most common methods of reading character-based data from a file in Java is using Scanner or BufferedReader. I also know that

12条回答
  •  渐次进展
    2020-11-22 02:59

    The Main Differences:

    1. Scanner

    • A simple text scanner which can parse primitive types and strings using regular expressions.
    • A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.

    Example

     String input = "1 fish 2 fish red fish blue fish";
     Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");
     System.out.println(s.nextInt());
     System.out.println(s.nextInt());
     System.out.println(s.next());
     System.out.println(s.next());
     s.close(); 
    

    prints the following output:

     1
     2
     red
     blue 
    

    The same output can be generated with this code, which uses a regular expression to parse all four tokens at once:

     String input = "1 fish 2 fish red fish blue fish";
    
     Scanner s = new Scanner(input);
     s.findInLine("(\\d+) fish (\\d+) fish (\\w+) fish (\\w+)");
     MatchResult result = s.match();
     for (int i=1; i<=result.groupCount(); i++)
         System.out.println(result.group(i));
     s.close(); `
    


    1. BufferedReader:

      • Reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines.

      • The buffer size may be specified, or the default size may be used. The default is large enough for most purposes.

    In general, each read request made of a Reader causes a corresponding read request to be made of the underlying character or byte stream. It is therefore advisable to wrap a BufferedReader around any Reader whose read() operations may be costly, such as FileReaders and InputStreamReaders. For example,

    BufferedReader in
       = new BufferedReader(new FileReader("foo.in"));
    

    will buffer the input from the specified file. Without buffering, each invocation of read() or readLine() could cause bytes to be read from the file, converted into characters, and then returned, which can be very inefficient. Programs that use DataInputStreams for textual input can be localized by replacing each DataInputStream with an appropriate BufferedReader.

    Source:Link

提交回复
热议问题