Java-读取文件的问题
我有这个功能:Java-读取文件的问题,java,io,Java,Io,我有这个功能: public static int checkRank(String lineToCompare){ int rank = 0; try{ // Open the file that is the first // command line parameter FileInputStream fstream = new FileInputStream("ranks.txt"); // Get th
public static int checkRank(String lineToCompare){
int rank = 0;
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
System.out.println("SPOT 0");
while ((strLine = br.readLine()) != null) {
//Compare the line with the line to compare (string)
System.out.println("SPOT 1");
if(strLine.trim().equals(lineToCompare)) {
//I found it! Read the next line...
final String lineAfter = br.readLine();
rank = Integer.parseInt(lineAfter);
System.out.println("SPOT 2");
}else{
rank = 0;
System.out.println("SPOT 3");
}
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
System.out.println("Username: " + lineToCompare + " | Rank: " + rank);
return rank;
}
我的ranks.txt
文件如下:
test1
2
test2
1
控制台输出(SPOT仅用于调试):
如您所见,如果它工作正常,它会说test1的秩为2。有人能帮我找出问题吗?在上一次循环迭代中,您正在用
0
覆盖rank
使用
Break中断循环代码>当你被击中时。你应该增加一个休息;在打印“SPOT 2”以结束while循环的行后的语句
如果没有中断,则在读取行“test2”时将秩设置为0,然后在读取行“1”时再次设置秩(while循环一直持续到文件末尾)。什么是lineToCompare
?@Jeffrey,lineToCompare=test1(如控制台输出中所示)。尝试添加中断;打印SPOT2后。您在阅读“test2”后将排名设置为0,然后在阅读“1”时再次设置排名。@DannyF247 Aha!代码框有一个滚动条。对不起that@ppalasek谢谢你把它修好了!!如果你想把它作为一个答案,这样我就可以接受它并为你争取代表,我将非常乐意:)
[Commands] SPOT 0
[Commands] SPOT 1
[Commands] SPOT 2
[Commands] SPOT 1
[Commands] SPOT 3
[Commands] SPOT 1
[Commands] SPOT 3
[Commands] Username: test1 | Rank: 0