开始从特定行读取文本文件

时间:2011-01-12 18:17:52

标签: java io text-files

是一种打开文本文件的方法,阅读几行,关闭它,重新打开它并从之前离开的行开始阅读?或者你总是要从顶部开始?

4 个答案:

答案 0 :(得分:1)

我每次都会从头顶开始。这是最简单的,可能不会慢得多。您可以使用RandomAccessFile,但是您必须使用自己的行读取器包装它(以及检查文件是否以不兼容的方式更改)

答案 1 :(得分:1)

你确定可以!这不是最快的方法,但它会起作用。顺便说一下,通过告诉您应该从文件开头重新处理来回答您的问题的人完全错过了您的问题。想要回到你离开的地方有很多理由。

以下是我编写的一些代码,它允许您存储计数器值,然后遍历文件直到您重新达到计数器值...此时循环生效并处理循环中的内容其余的行。

干杯!

//define input text file
def file = new File('C:\\inputtextfile.txt')
//define file for the last referenced counter
def CountFile = new File ('C:\\prime\\lastcount.txt')

//if the counter was null set it to zero
if (CountFile.eachLine({it}) == null){
CountFile.write('0')
}

//read the counter into a value
StartLine = CountFile.eachLine( {it} ) as long
//set the first line of the file
lineCount=0

file.eachLine { line  ->
if (lineCount >= StartLine){


//write the counter to a text file
////////////////////////////////////////////////////////////////
CountFile.write(lineCount.toString())
    lineCount++
///////////////////////////////////////////////////////////////
}

答案 2 :(得分:0)

我很确定每次打开文件时,它都会从头开始。

答案 3 :(得分:0)

您不能只在外部保存行号并跳转到/寻找所需的位置吗?