Reading Specific Lines in Java
In Java, you can use the readLine() method of the BufferedReader class to read a text file line by line. Here is an example code demonstrating how to use the readLine() method to read the content of a specific line number:
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();
}
}
}
In the example above, the file path and line number to read are first specified. Then, a BufferedReader is used to read the file and its contents line by line. When the line number being read matches the specified line number, the content of that line is output. Finally, a try-with-resources statement is used to handle any exceptions that may occur during the file reading process.