gpt4 book ai didi

Java - 从文件中获取行

转载 作者:行者123 更新时间:2023-11-30 06:30:18 25 4
gpt4 key购买 nike

下面是我当前的功能。如果找到 lineToCompare,它工作正常并返回 true。

public static int checkrank(String lineToCompare){
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("ranks.txt");

// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));

String strLine;
//Read File Line By Line

while ((strLine = br.readLine()) != null) {
//Compare the line with the line to compare (string)
if(strLine.trim().compareTo(lineToCompare) == 0)
return true;
}

//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}

return false;

}

但是,在找到 lineToCompare 之后,我需要它来获取行。

这是一个示例文本文件:

xXPwnageLolXx
1
SomethingTest
0
AnotherSomething
3

我需要它来找到文本行 (lineToCompare),然后在找到的行之后返回数字。我该怎么做?

最佳答案

while ((strLine = br.readLine()) != null)   {
//Compare the line with the line to compare (string)
if(strLine.trim().compareTo(lineToCompare) == 0) {
//I found it! Read the next line...
final String lineAfter = br.readLine();
return Integer.parseInt(lineAfter);
}
}

我已编辑此片段以包含 Dowards 建议。局部变量是不必要的,我只是为了便于阅读而保留它。

关于Java - 从文件中获取行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10577660/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com