Programming Tutorials

FileInputStream - sample program in Java

By: Sam Chen in Java Tutorials on 2007-09-14  

The FileInputStream class creates an InputStream that you can use to read bytes from
a file. Its two most common constructors are shown here:

FileInputStream(String filepath)
FileInputStream(File fileObj)

Either can throw a FileNotFoundException. Here, filepath is the full path name of a file, and fileObj is a File object that describes the file. The following example creates two FileInputStreams that use the same disk file and each of the two constructors:

FileInputStream f0 = new FileInputStream("/autoexec.bat")
File f = new File("/autoexec.bat");
FileInputStream f1 = new FileInputStream(f);

Although the first constructor is probably more commonly used, the second allows us to closely examine the file using the File methods, before we attach it to an input stream. When a FileInputStream is created, it is also opened for reading. FileInputStream overrides six of the methods in the abstract class InputStream. The mark() and reset() methods are not overridden, and any attempt to use reset() on a FileInputStream will generate an IOException.

The next example shows how to read a single byte, an array of bytes, and a subrange array of bytes. It also illustrates how to use available() to determine the number of bytes remaining, and how to use the skip() method to skip over unwanted bytes. The program reads its own source file, which must be in the current directory in this case the name of the file is FileInputStreamDemo.java.

// Demonstrate FileInputStream.
import java.io.*;

class FileInputStreamDemo {
    public static void main(String args[]) throws Exception {
        int size;
        InputStream f = new FileInputStream("FileInputStreamDemo.java");
        System.out.println("Total Available Bytes: " +
                (size = f.available()));
        int n = size / 40;
        System.out.println("First " + n + " bytes of the file one read() at a time");
        for (int i = 0; i < n; i++) {
            System.out.print((char) f.read());
        }
        System.out.println("Still Available: " + f.available());
        System.out.println("Reading the next " + n +
                " with one read(b[])");
        byte b[] = new byte[n];
        if (f.read(b) != n) {
            System.err.println("couldn't read " + n + " bytes.");
        }
        System.out.println(new String(b, 0, n));
        System.out.println("Still Available: " + (size = f.available()));
        System.out.println("Skipping half of remaining bytes with skip()");
        f.skip(size / 2);
        System.out.println("Still Available: " + f.available());
        System.out.println("Reading " + n / 2 + " into the end of array");
        if (f.read(b, n / 2, n / 2) != n / 2) {
            System.err.println("couldn't read " + n / 2 + " bytes.");
        }
        System.out.println(new String(b, 0, b.length));
        System.out.println("Still Available: " + f.available());
        f.close();
    }
}

Here is the output produced by this program:

Total Available Bytes: 1493
First 37 bytes of the file one read() at a time
// Demonstrate FileInputStream.
imStill Available: 1456
Reading the next 37 with one read(b[])
port java.io.*;
class FileInputStr
Still Available: 1419
Skipping half of remaining bytes with skip()
Still Available: 710
Reading 18 into the end of array
port java.io.*;
r.println("couldn'r
Still Available: 692

This somewhat contrived example demonstrates how to read three ways, to skip input, and to inspect the amount of data available on a stream.

This tutorial is an extract from the "The Complete Reference Part 2 by Herbert Schildt".






Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in Java )

Latest Articles (in Java)