[英]How to read from a specific line of a file
I have a text file (called data.txt
, which has 350 lines) 我有一个文本文件(称为data.txt
,具有350行)
How can I find the text on a given line of the file? 如何在文件的给定行上找到文本? For example: 例如:
int imageVariable = 5;
String imageText = nthLineOfFile(imageVariable);
textView1.setText(imageText);
I'm trying to write the String nthLineOfFile(int image)
function. 我正在尝试编写String nthLineOfFile(int image)
函数。
Thanks 谢谢
You may try this: 您可以尝试以下方法:
String str = FileUtils.readLines(file).get(lineNumber);
or you may use the conventional way by using BufferedReader
class: 或者您可以通过使用BufferedReader
类使用常规方式:
BufferedReader r = new BufferedReader(new FileReader(file));
for (int i = 0; i < lineNumber - 1; i++)
{
r.readLine();
}
return r.readLine();
You can use Scanner
: 您可以使用Scanner
:
Scanner fileIn = new Scanner(your file);
for (int i = 0; i < lineNum - 1; i++) {
fileIn.nextLine(); // ignore
}
nthLine = fileIn.nextLine();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.