SoFunction
Updated on 2025-04-14

Detailed explanation of the use of Scanner, BufferedReader and StreamTokenizer in Java

1. Scanner usage and analysis

Introduction:

ScannerIt is a Java used to parse primitive types (such asintdoubleetc.) and string classes. It usually reads data one by one from the input stream and parses it, supporting the use of multiple delimiters. Its method is relatively flexible and can handle different types of data input.

Common methods:

  • nextLine(): Read a line of text.
  • nextInt(): Read an integer.
  • nextDouble(): Read a floating point number.
  • next(): Read a word.

performance:

ScannerCompared withBufferedReaderIt is slightly inferior in performance, especially when a large amount of data is input, because format checks and parses are required every time you read.

Error handling:

ScannerWhen reading data that does not conform to the format, an exception is usually thrown and needs to be managed through exception handling.

Applicable scenarios

Suitable for simple, format-specific inputs, especially when processing inputs of basic data types.

Code example: Basic use of Scanner

import ;
public class ScannerExample {
    public static void main(String[] args) {
        Scanner scanner = new Scanner();
        ("Enter a string:");
        String inputString = ();  // Read a line of text        ("You entered: " + inputString);
        ("Enter an integer:");
        int inputInt = ();  // Read integers        ("You entered the number: " + inputInt);
        ("Enter a double:");
        double inputDouble = ();  // Read floating point numbers        ("You entered the double: " + inputDouble);
        ();
    }
}

2. Usage and analysis of BufferedReader

Introduction:

BufferedReaderIt is a class in Java for reading character input streams. It provides buffering to reduce I/O operations on each read, thereby improving performance. generally,BufferedReaderUsed to read data line by line.

Common methods:

  • readLine(): Read a line of text.
  • read(): Read a single character.

performance:

BufferedReaderThe performance of reading large amounts of data is improved through the buffering mechanism, especially when processing file readings.

Error handling:

BufferedReaderFor incorrect inputs, no exception is usually thrown, but returnsnull, requires explicit judgment and processing.

Applicable scenarios:

Suitable for handling large amounts of text input, especially in scenarios where performance requirements are high. It is suitable for reading large chunks of data from files or standard input.

Code example: Basic use of BufferedReader

import ;
import ;
import ;
public class BufferedReaderExample {
    public static void main(String[] args) {
        BufferedReader reader = new BufferedReader(new InputStreamReader());
        try {
            ("Enter a line of text:");
            String input = ();  // Read a line of text            ("You entered: " + input);
        } catch (IOException e) {
            ();
        } finally {
            try {
                ();
            } catch (IOException e) {
                ();
            }
        }
    }
}

3. Use and analysis of StreamTokenizer

Introduction:

StreamTokenizerIt is a class in Java used to split the input stream into tokens. It is suitable for parsing structured text by reading the character stream and cutting the characters in the input stream into meaningful words, numbers, etc. according to specified rules.

Common methods:

  • nextToken(): Read the next tag.
  • ttype: The type of mark (such as words, numbers, etc.).
  • sval: The string value of the current tag.
  • nval: The numeric value of the current mark.

performance:

StreamTokenizerIt performs better when parsing text because it reads input character-by-character input in the form of a stream and does not take up too much memory.

Error handling:

StreamTokenizerSkip it when unrecognized characters are encountered until the next valid markup. It usually does not throw an exception.

Applicable scenarios:

Suitable for scenarios where precise control of tokenized input streams is required, especially when it comes to text analysis and parsing.

Code example: Basic use of StreamTokenizer

import .*;
import .*;
public class Main {
    static StreamTokenizer st = new StreamTokenizer(new BufferedReader(new InputStreamReader()));
    public static void main(String[] args) throws IOException {
        int n = nextInt();
    }
    public static int nextInt() throws IOException {
        ();
        return (int);
    }
}
import ;
import ;
import ;
import ;
public class StreamTokenizerExample {
    public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader());
        ("Enter some text:");
        processTokens(reader);  // Process input marks    }
    /**
      * Process the entered text and print each marker.
      * @param reader Input Stream
      * @throws IOException The exception thrown when reading the stream
      */
    public static void processTokens(BufferedReader reader) throws IOException {
        // Create StreamTokenizer object        StreamTokenizer tokenizer = new StreamTokenizer(reader);
        // traverse the input stream and process each marker        while (() != StreamTokenizer.TT_EOF) {
            processTokenByType(tokenizer);  // Process according to the tag type        }
    }
    /**
      * Process input according to different tag types
      * @param tokenizer StreamTokenizer object
      */
    public static void processTokenByType(StreamTokenizer tokenizer) {
        try {
            switch () {
                case StreamTokenizer.TT_WORD:
                    ("Word: " + );  // Process words                    break;
                case StreamTokenizer.TT_NUMBER:
                    ("Number: " + );  // Process numbers                    break;
                case StreamTokenizer.TT_EOL:
                    ("End of line encountered.");  // Process line ending characters                    break;
                case StreamTokenizer.TT_EOF:
                    // EOF does not need to be processed                    break;
                default:
                    ("Other: " + (char) );  // Process other characters                    break;
            }
        } catch (IOException e) {
            // Unified exception throw            throw new RuntimeException("Error processing the token", e);
        }
    }
}

Summarize

  • ScannerSuitable for simple, format-specific inputs, especially when dealing with basic data types. Its advantage lies in flexibility, but its performance is relatively highBufferedReaderDifference.
  • BufferedReaderSuitable for processing large chunks of text input, especially when processing file data. Through the buffering mechanism,BufferedReaderProvides high performance.
  • StreamTokenizerApplicable to complex text parsing, can segment input streams according to different lexical rules, and can flexibly process various markups.

This is all about this article about Scanner, BufferedReader and StreamTokenizer in Java. For more related contents of Java Scanner, BufferedReader and StreamTokenizer, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!