Reputation: 47
Consider the following code snippet for reading a file in Java/Android:
FileInputStream fis = openFileInput("myfile.txt");
BufferedInputStream bis = new BufferedInputStream(fis);
StringBuffer b = new StringBuffer();
while (bis.available()!=0) {
char c = (char) bis.read();
b.append(c);
}
bis.close();
fis.close();
I am talking about available() method in the condition of while loop. I looked the API documentation for that method and I have the following questions:
How the iteration inside the the while loop is happening, i.e. how is the file pointer moving to another chunk of data during each iteration of while loop? This is not specified in the API documentation.
How can I figure out which method of which class should I use to accomplish a task?
Upvotes: 2
Views: 188
Reputation: 2219
The available method returns an int as an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream.
That while loop
is iterating till the end of the file essentially, when there is no bytes there is no file.
Here is some documentation: http://docs.oracle.com/javase/7/docs/api/java/io/BufferedInputStream.html
Upvotes: 4
Reputation: 337
The bis.available functions checks for end of file. in each iteration of the while loop when u do bis.read() the file pointer reads one character and automatically moves on to the next one.
As far as your query about which method to use. just look up the parameters that the function takes. and what u need to accomplish. its not very difficult figuring that out.
Upvotes: 1