简体   繁体   中英

How to find if a line exists in the BufferedReader file?

I have this method in Java, which is called within another method's try block. importFormat returns the class with assigned values (//do what is needed) in the try block. The method should read a file line by line. In case the method call to the method with try block is called more times than are the lines in a file, the importFormat() should return null.

I tried to check it with if block, although it doesn't do much and the ClassName is always returned. It seems the class stores always a first line from the file.

private ClassName importFormat(BufferedReader br) throws IOException, ParseException {

String out;
Track t = new ClassName();

if((out = br.readLine()) == null) return null;

    //do what is needed

    }else{
        t = null; //here I unsuccessfully tried to force the method to again return null, no luck
        System.err.print(out);
        throw new ParseException("", 0);
    }

return t;

}

I have tried also the br.ready() method, it didn't make any difference

EDIT: I noticed I have reproduced the code incorrectly, I'm sorry for that. Here it should be clearer Minimal reproducible code:

private ClassName foo(BufferedReader br) throws IOException {
    ClassName t = new ClassName();
    String out = null;

    out = br.readLine();
    if(out.equals(null)) return null; //handle the case where there's no more line to read

    if(/*!string red from BufferedReader.isEmpty()*/){
        //do something
    }else{
        t = null; //ensure that null would be returned
        //do something more unrelated to this question
    }
    return t;
}

I dont realy understand your question but I think you should not compare like this:

if((out = br.readLine()) == null) return null;

To compare string in java, let use str1.equals(str2) instead. So I think you should try:

if(out.equals(br.readLine())) {
    //do sth here because "out" exists in BufferReader.
} else {
    System.out.println("Continue searching...\n");
}

return t;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM