Using input streams usually involves 4 basic steps:
So in this section, we will familiarize ourselves with the above four basic steps by studying the file byte input stream.
If the file reading requirements are relatively simple, you can use the FileInputStream class (file byte input stream), which is a subclass of the InputStream class (reading files in bytes). The instance methods of this class are all from InputStream The class is inherited.
We can create an input stream pointing to a file using the following constructor methods of the FileInputStream class.
FileInputStream(Stringname);FileInputStream(Filefile);
The first constructor uses the given file name to create a FileInputStream stream; the second constructor uses a File object to create a FileInputStream stream. The file specified by the parameters name and file is called the source of the input stream.
The FileInputStream input stream opens a channel to the file (the source is this file and the input stream points to this file). When creating an input stream, errors (also known as exceptions) may occur. For example, the input stream may point to a file that does not exist.
When an I/O error occurs, Java generates an error signal, which uses an IOException (IO exception) object to represent the error signal. The program must create the input stream in the try block part of the try-catch statement, and detect and handle this exception in the catch block part. For example, to read a file named hello.txt, create a file input stream in.
try{FileInputStreamin=newFileInputStream(hello.txt);//Create an input stream pointing to the file hello.txt}catch(IOExceptione){System.out.println(Filereaderror:+e);}
or
Filef=newFile(hello.txt);//Specify the source of the input stream try{FileInputStreamin=newFileInputstream(f);//Create an input stream pointing to the source}catch(IOExceptione){System.out.println(Filereaderror:+e) ;}