例如,我想从行号20056读取文本文件,直到第1159450行,并将其输出到输出窗口,但我不知道如何操作,因为方法line.readline()
从第一行开始。
这是我的代码:
String line;
int currentLineNo = 1;
int startLine = 20056;//40930;
int endLine = 1159450;
FileReader file = new FileReader("yourfilepath");
BufferedReader reader = new BufferedReader(file);
PrintWriter writer = new PrintWriter("yourfilepath", "UTF-8");
while (currentLineNo < startLine) {
currentLineNo++;
}
while(currentLineNo >= startLine && currentLineNo <= endLine) {
// System.out.println(currentLineNo);
line = reader.readLine();
System.out.println(line);
// writer.println(line);
currentLineNo++;
}
reader.close();
writer.close();
如何仅从第20056行打印到第1159450行并将其输出到输出窗口?
答案 0 :(得分:1)
String line;
int currentLineNo = 1;
int startLine = 20056;//40930;
int endLine = 1159450;
FileReader file = new FileReader("yourfilepath");
BufferedReader reader = new BufferedReader(file);
PrintWriter writer = new PrintWriter("yourfilepath", "UTF-8");
while (currentLineNo <= endLine)
{
line = reader.readLine();
if(currentLineNo >= startLine && currentLineNo<=endLine)
{ System.out.println(line); }
currentLineNo++;
}
reader.close();
writer.close();
答案 1 :(得分:0)
(代表OP发布解决方案)。
我只需要删除第一个while循环。
String line;
int currentLineNo = 1;
int startLine = 20056;//40930;
int endLine = 1159450;
FileReader file = new FileReader("yourfilepath");
BufferedReader reader = new BufferedReader(file);
PrintWriter writer = new PrintWriter("yourfilepath", "UTF-8");
while(currentLineNo<=endLine)
{
line = reader.readLine();
if(currentLineNo >= startLine && currentLineNo<=endLine)
{ System.out.println(line); }
currentLineNo++;
}
reader.close();
writer.close();
归功于Jay Hamilton。