有人可以帮我逐行读取文件,
我有这段代码 - 但是这段代码会打印所有内容.我需要逐行显示第5(或特定),因此我想动态访问和打印任何行.我需要打印文本文件的第5行.
//read from file
myFile = new File("C:\\Documents and Settings\\ABCEDFG\\Desktop\\soapUI\\params.txt")
printFileLine = { log.info "File line: " + it }
myFile.eachLine(0, printFileLine)
Run Code Online (Sandbox Code Playgroud)
请帮助 - 提前感谢您的帮助!
^谢谢
这是邋and和浪费,但你可以做到
log.info "Line 5: " + myFile.readLines().get(4)
Run Code Online (Sandbox Code Playgroud)
如果您不希望所有内容都在内存中,您可以执行以下操作:
String readLine( File f, int n ) {
String line = null
f.withReader { r ->
while( n-- > 0 && ( ( line = r.readLine() ) != null ) ) ;
}
line
}
Run Code Online (Sandbox Code Playgroud)
然后,打印第 5 行:
File infile = new File("C:\\Documents and Settings\\ABCEDFG\\Desktop\\soapUI\\params.txt")
String line = readLine( infile, 5 )
println line
Run Code Online (Sandbox Code Playgroud)
但是,如果您想以随机顺序访问方式读取多行,这可能会很浪费,因为您每次都会从头开始对文件进行后台处理。但是,如果由于太大而无法将其加载到内存中,则您无能为力