How to use FileInputStream in Java?
In Java, you can use the FileInputStream class to read the contents of a file. The general steps for using FileInputStream are as follows:
- Instantiate a FileInputStream object by passing the file path to be read as a parameter. For example:
- Create a FileInputStream to read from the file path.
- Create a byte array to store the data read from a file. For example:
- Create an array called buffer with a length of 1024 bytes.
- Reading file content using the read method of FileInputStream and storing the read data in a byte array. The read method returns the number of bytes read, and if it returns -1, it indicates that the end of the file has been reached. For example:
- The variable “bytesRead” stores the value returned by the method “fis.read(buffer)”.
- Utilize a while loop to continuously read the file content until reaching the end of the file. For example:
- Continue reading the next part of data until no more bytes are read.
- Handle the read data within the loop. For example, you can convert the read data to a string and print it out.
- Create a new string by converting the data read from the buffer, and then print it.
- After reading the contents of the file, it is necessary to close the FileInputStream to release resources. For example:
- Close the file input stream.
Note: When using FileInputStream to read a file, it is necessary to handle IOException.