Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

The Byte Streams FileInputStream

Ramesh Fadatare edited this page Aug 14, 2018 · 4 revisions

The FileInputStream class creates an InputStream that you can use to read bytes from a file. It is used for reading byte-oriented data (streams of raw bytes) such as image data, audio, video etc. You can also read character-stream data. But, for reading streams of characters, it is recommended to use FileReader class.

FileInputStream Class Constructor

  1. FileInputStream(File file) - Creates a FileInputStream by opening a connection to an actual file, the file named by the File object file in the file system.
  2. FileInputStream(FileDescriptor fdObj) - Creates a FileInputStream by using the file descriptor fdObj, which represents an existing connection to an actual file in the file system.
  3. FileInputStream(String name) - Creates a FileInputStream by opening a connection to an actual file, the file named by the path name name in the file system.

From above constructors, two commonly used 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("/execute.bat");
File f = new File("/execute.bat");
FileInputStream f1 = new FileInputStream(f);

FileInputStream APIs/Methods

  • int available() - Returns an estimate of the number of remaining bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream.
  • void close() - Closes this file input stream and releases any system resources associated with the stream.
  • protected void finalize() - Ensures that the close method of this file input stream is called when there are no more references to it.
  • FileChannel getChannel() - Returns the unique FileChannel object associated with this file input stream.
  • FileDescriptor getFD() - Returns the FileDescriptor object that represents the connection to the actual file in the file system being used by this FileInputStream.
  • int read() - Reads a byte of data from this input stream.
  • int read(byte[] b) - Reads up to b.length bytes of data from this input stream into an array of bytes.
  • int read(byte[] b, int off, int len) - Reads up to len bytes of data from this input stream into an array of bytes.
  • long skip(long n) - Skips over and discards n bytes of data from the input stream.

Demonstrate FileInputStream Example

In this example demonstrate the usage of few important methods of FileInputStream class.

This example shows how to read a single byte, an array of bytes, and a subrange of an 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.

Notice that it uses the try-with-resources statement to automatically close the file when it is no longer needed.

import java.io.FileInputStream;
import java.io.IOException;
/**
 * The class demonstrate the usage of FileInputStream class methods.
 * @author javaguides.net
 *
 */
public class FileInputStreamDemo {
	public static void main(String args[]) {
		int size;
		// Use try-with-resources to close the stream.
		try (FileInputStream 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("\nStill 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("\nStill 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("\nStill Available: " + f.available());
		} catch (IOException e) {
			System.out.println("I/O Error: " + e);
		}
	}
}

Output:

Total Available Bytes: 1523
First 38 bytes of the file one read() at a time
package com.javaguides.javaio.book;
Still Available: 1485
Reading the next 38 with one read(b[])
import java.io.FileInputStream;
impo
Still Available: 1447
Skipping half of remaining bytes with skip()
Still Available: 724
Reading 19 into the end of array
import java.io.Filrintln("couldn’t re
Still Available: 705

More Examples

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class FileInputStreamExample {
	public static void main(String[] args) {
		File file = new File("sample.txt");
		try (FileInputStream fis = new FileInputStream(file)) {
			int content;
			while ((content = fis.read()) != -1) {
				// convert to char and display it
				System.out.print((char) content);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

Output:

There is some content in file 
newline added to existing file

Reference

FileInputStream Javadoc 8

Clone this wiki locally

AltStyle によって変換されたページ (->オリジナル) /