In the previous section, we learned how to construct a file byte input stream. In this section, we continue to learn how to use the input stream to read bytes and close the stream.
The purpose of the input stream is to provide a channel for reading data from the source. The program can read the data from the source through this channel. The file byte stream can call the read method inherited from the parent class to read the file sequentially, as long as the stream is not closed. Each call to the read method sequentially reads the remaining contents of the file until the end of the file or the file byte input stream is closed.
The read method of the byte input stream reads the data in the source in bytes.
The input stream calls this method to read a single byte of data from the source. This method returns the byte value (an integer between 0 and 255). If the byte is not read, it returns -1.
The input stream calls this method to try to read b.length bytes from the source into the byte array b, and returns the actual number of bytes read. If the end of the file is reached, -1 is returned.
The input stream calls this method to attempt to read len bytes from the source into byte array b, and returns the actual number of bytes read. If the end of the file is reached, -1 is returned, and the parameter off specifies a position in the byte array to start storing the read data.
Note : The FileInputStream stream reads the file sequentially. As long as the stream is not closed, each call to the read method reads the rest of the source content sequentially until the end of the source or the stream is closed.
Input streams all provide a closing method close() . Although all open streams will be automatically closed when the program ends, it is still a good habit to explicitly close any open streams after the program has finished using the stream. If open streams are not closed, another program may not be allowed to manipulate the resources used by those streams.
For example:
importjava.io.*;publicclassMain{publicstaticvoidmain(Stringargs[]){intn=-1;byte[]a=newbyte[100];try{Filef=newFile(Main.java);InputStreamin=newFileInputStre am(f);while((n=in.read(a,0,100))!=-1){Strings=newString(a,0,n);System.out.print(s);}in.close( );}catch(IOExceptione){System.out.println(FilereadError+e);}}}
Note : When converting the read bytes into a string, the actual read bytes must be converted into a string, such as in the above example:
Strings=newString(a,0,n);
cannot be written as:
Strings=newString(a,0,100);