The FileInputStream class | Managing Input/Output Files in Java

The FileInputStream class

• Is part of the java.io package
• Is an extension of the InputStream class, an abstract class that describes the behavior of an input stream
• Is a low-level class that can be used to read individual, 8-bit bytes from a stream
• Has several constructors. The most frequently used constructs a FileInputStream object from a File object that encapsulates the file’s pathname. For example, if fd is the reference of a File object
FileInputStream in = new FileInputStream(fd);
It will construct a FileInputStream object for reading bytes from the file. Because a checked, IOException may occur, the statement should be enclosed in a try block with an appropriate catch.
• it has a few useful methods. The most used are:
Because a checked, IOException may occur, calls to these methods should be enclosed in a try block with an appropriate catch. Consult the Java API documentation for more details.
• Example. The following program can be used to read byte values from a disk file. It can be used to display the values stored by the previous sample program.
import java.io.*;
public class AppFIS
{
public static void main(String[] args)
{

// Local variables and object references.

File fd;
FileInputStream in;

// Get the path name from the user.

System.out.print(“Enter the file’s complete path name: “);
fd = new File(Keyboard.readString());

// Try to read data from the input stream.

try
{

// Open an input stream for the file.

in = new FileInputStream(fd);

// This loop reads a byte from the stream and displays
// its value. The loop ends when no more bytes are available.

while (in.available() > 0)
{
System.out.println(in.read());
}

// Close the stream.

in.close();
System.out.println(“Closed – ” + fd.getPath());
}

// Catch an IOException if one is thrown.

catch (IOException e)
{
System.out.println(e.getMessage());
}
}
}