質問

I have a method that receives a string with a filepath, and i have created all the code for reading the file, with the try a catch blocks, somthing very simple like this:

private static String readLineFormFile(String filename){

    File filepath=  new File(filename);
    BufferedReader reader = null;
    String line =null;      

    try{

    reader = new BufferedReader(new FileReader(filepath));

    line=reader.readLine();
    }
    catch (FileNotFoundException fe1){
        System.out.println(filename+" file Not Found");
    }
    catch (IOException ie1) {
        System.out.println("Error Reading File "+filename);
    }   
    finally{
        try{
        reader.close();


    }catch(IOException ie2){
        System.out.println("Error closing file "+filename);
    }
 }
    return line;
}

Now if I call this method on a file 2 times, will the buffereader still know the line I was after I close it for the first time?

役に立ちましたか?

解決

will the buffereader still [k]now the line i was after i close it for the first time?

No. You will be reading from the beginning of the file each time.

他のヒント

No.

Each time you run the method, a new BufferedReader object is created. When the method ends, the object is destroyed, and a new one is created the next time you run the method.

The information about where you're up to in the reading is stored in the BufferedReader object, and is not shared by all such objects.

What object instance would that be? The BufferedReader instance is created twice; once for each call, using the new keyword on the constructor. reader is a local variable that goes out of scope when the method is exited.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top