温馨提示×

java怎么用readline读取指定行

小亿
99
2024-02-29 09:46:14
栏目: 编程语言

在Java中,可以使用BufferedReader类的readLine()方法来逐行读取文本文件。以下是一个示例代码,演示如何使用readLine()方法读取指定行号的内容:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadSpecificLine {
    public static void main(String[] args) {
        String filePath = "path/to/file.txt";
        int lineNumber = 5; // 读取第5行的内容

        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String line;
            int currentLine = 0;

            while ((line = br.readLine()) != null) {
                currentLine++;
                if (currentLine == lineNumber) {
                    System.out.println("Line " + lineNumber + ": " + line);
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

在上面的示例中,首先指定了要读取的文件路径和行号。然后使用BufferedReader来读取文件,并逐行读取内容。当读取的行号等于指定的行号时,输出该行的内容。最后使用try-with-resources语句来处理文件读取时可能发生的异常。

0