Read Input Character-by-Character in Java – 在 Java 中逐字读取输入字符

最后修改: 2024年 1月 15日

中文/混合/英文(键盘快捷键:t)

1. Introduction

1.导言

In many Java applications, we need to read the input data character by character since it is a common task, especially when working with lots of data from a stream source.

在许多 Java 应用程序中,我们需要逐个字符地读取输入数据,因为这是一项常见的任务,尤其是在处理来自流源的大量数据时。

In this tutorial, we’ll look at various ways to read one character at a time in Java.

在本教程中,我们将了解在 Java 中一次读取一个字符的各种方法。

2. Using BufferedReader for Console Input

2.使用 BufferedReader 进行控制台输入

We can utilize BufferedReader to perform reading character-by-character from the console. Note that this method is helpful if we seek to read characters interactively.

我们可以利用 BufferedReader 从控制台逐个读取字符。请注意,如果我们希望以交互方式读取字符,此方法将非常有用。

Let’s take an example:

让我们举个例子:

@Test
public void givenInputFromConsole_whenUsingBufferedStream_thenReadCharByChar() throws IOException {
    ByteArrayInputStream inputStream = new ByteArrayInputStream("TestInput".getBytes());
    System.setIn(inputStream);

    try (BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in))) {
        char[] result = new char[9];
        int index = 0;
        int c;
        while ((c = buffer.read()) != -1) {
            result[index++] = (char) c;
        }

        assertArrayEquals("TestInput".toCharArray(), result);
    }
}

Here, we simply simulate the console input by instantiating a ByteArrayInputStream with the “TestInput” content. Then, we read characters from System.in using BufferedReader. Afterward, we use the read() method to read one character as integer code and cast it into a char. Finally, we use the assertArrayEquals() method to verify that the read characters match the expected input.

在这里,我们只需通过实例化一个包含 “TestInput “内容的 ByteArrayInputStream 来模拟控制台输入。然后,我们使用 BufferedReaderSystem.in 中读取字符。然后,我们使用 read() 方法以整数代码读取一个字符,并将其转换为 char 方法。最后,我们使用 assertArrayEquals() 方法来验证读取的字符是否与预期的输入相匹配。

3. Using FileReader for Reading from Files

3.使用 FileReader 读取文件

When working on files, FileReader is an appropriate choice for reading character by character:

在处理文件时,FileReader 是逐个字符读取的合适选择:

@Test
public void givenInputFromFile_whenUsingFileReader_thenReadCharByChar() throws IOException {
    File tempFile = File.createTempFile("tempTestFile", ".txt");
    FileWriter fileWriter = new FileWriter(tempFile);
    fileWriter.write("TestFileContent");
    fileWriter.close();

    try (FileReader fileReader = new FileReader(tempFile.getAbsolutePath())) {
        char[] result = new char[15];
        int index = 0;
        int charCode;
        while ((charCode = fileReader.read()) != -1) {
            result[index++] = (char) charCode;
        }

        assertArrayEquals("TestFileContent".toCharArray(), result);
    }
}

In the above code, we create a temporary test file with the content “tempTestFile” for simulation. Then, we use a FileReader to establish a connection to the file specified by its path using the tempFile.getAbsolutePath() method. Within a try-with-resources block, we read the file character by character.

在上述代码中,我们创建了一个内容为 “tempTestFile “的临时测试文件用于模拟。然后,我们使用 FileReader 方法 tempFile.getAbsolutePath() 与文件路径指定的文件建立连接。在try-with-resources块中,我们逐个字符读取文件。

4. Using Scanner for Tokenized Input

4.使用扫描仪进行标记化输入

For a more dynamic approach that allows tokenized input, we can use Scanner:

对于允许标记化输入的更动态方法,我们可以使用 Scanner

@Test
public void givenInputFromConsole_whenUsingScanner_thenReadCharByChar() {
    ByteArrayInputStream inputStream = new ByteArrayInputStream("TestInput".getBytes());
    System.setIn(inputStream);

    try (Scanner scanner = new Scanner(System.in)) {
        if (scanner.hasNext()) {
            char[] result = scanner.next().toCharArray();
            assertArrayEquals("TestInput".toCharArray(), result);
        }
    }
}

We simulate the console input in the above test method by instantiating a ByteArrayInputStream with the “TestInput” content. Then, we utilize the hasNext() method to verify if there is another token. Afterward, we utilize the next() method to fetch the current one as a String.

在上述测试方法中,我们通过实例化具有 “TestInput “内容的 ByteArrayInputStream 来模拟控制台输入。然后,我们使用 hasNext() 方法来验证是否存在另一个标记。然后,我们使用 next() 方法以 String 的形式获取当前令牌。

5. Conclusion

5.结论

In conclusion, we explored diverse methods in Java for reading characters, covering interactive console input using BufferedReader, file-based character reading with FileReader, and tokenized input handling via Scanner, offering developers versatile approaches to process character data efficiently in various scenarios.

总之,我们探索了 Java 中读取字符的各种方法,包括使用 BufferedReader 进行交互式控制台输入、使用 FileReader 进行基于文件的字符读取,以及通过 Scanner 处理标记化输入,为开发人员提供了在各种场景中高效处理字符数据的多种方法。

As always, the complete code samples for this article can be found over on GitHub.

与往常一样,本文的完整代码示例可在 GitHub 上找到