Java - 读取文件的问题

时间:2012-05-15 00:25:14

标签: 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 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”仅用于调试):

[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

正如您所看到的,如果它正常工作,它会说test1的等级为2.有人可以帮我识别问题吗?

2 个答案:

答案 0 :(得分:1)

您在最后一次循环迭代中用rank覆盖0

当你受到攻击时,使用break;突破循环。

答案 1 :(得分:1)

你应该添加休息时间;打印出“SPOT 2”以结束while循环的行之后的语句。

如果没有中断,则在读取“test2”行时将等级设置为0,然后在读取“1”行时再次将等级设置为0(while循环一直持续到文件结束)。