java读取txt文件中某几行并输出到屏幕上
时间: 2024-03-23 08:43:32 浏览: 20
要读取txt文件中的多行内容,可以在while循环中使用一个计数器来记录当前行号,当行号在需要读取的范围内时,将该行内容输出到屏幕上。具体实现方法如下:
```java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadTxtFile {
public static void main(String[] args) {
String filePath = "test.txt"; // txt文件的路径
int startLine = 3; // 要读取的起始行号,假设为第3行
int endLine = 5; // 要读取的结束行号,假设为第5行
try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
String line;
int currentLine = 1;
while ((line = br.readLine()) != null) {
if (currentLine >= startLine && currentLine <= endLine) {
System.out.println(line);
}
if (currentLine > endLine) {
break;
}
currentLine++;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
其中,startLine和endLine分别表示要读取的起始行号和结束行号。在while循环中,使用readLine()方法逐行读取文件,同时记录当前行号。当当前行号在需要读取的范围内时,将该行内容输出到屏幕上。当当前行号大于结束行号时,跳出循环。最后记得要关闭文件流。