Java FileInputStream

Filed Under: Java
Java FileInputStream

1. Java FileInputStream Class

  • Java FileInputStream class is a part of java.io package.
  • FileInputStream obtains input bytes from a file in a file system.
  • FileInputStream is used for reading streams of raw bytes such as image data.
  • FileInputStream is a subclass of InputStream class.

2. FileInputStream Class Hierarchy

FileInputStream Class Hierarchy

3. FileInputStream Constructors

FileInputStream provides many methods for reading bytes from a file and we can create an instance of FileInputStream using below constructors.

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

4. FileInputStream Methods

Let’s have a look at the below methods of FileInputStream class.

  1. available(): This method returns an estimate of the number of remaining bytes that can be read from input stream without blocking by the next invocation of method for this input stream.
  2. close(): This method closes this file input stream and release any system resources associated with the stream. If this stream has an associated channel then channel is closed as well.
  3. finalize(): This method ensures that the close() method of this file input stream is called when there are no more reference to it.
  4. getChannel(): This method returns the unique FileChannel object associated with this file input stream. The initial position of the returned channel will be equal to the number of bytes read from the file and reading bytes from this stream will increment the channel’s position.
  5. getFD(): This method returns the FileDescriptor object that represents the connection to the actual file in the file system being used by this FileInputStream.
  6. read(): This method reads a byte of data from this input stream and returns the next byte of data or -1 if the end of file is reached.
  7. read(byte[] b): This method reads byte of data up to the length of specified array(b.length) from this input stream into specified array of bytes and returns the total number of bytes read into the buffer or -1 if the end of file is reached.
  8. read(byte[] b, int off, int len): This method reads bytes of data up to specified len from this input stream into specified array of bytes. If specified len is not zero, the method blocks until some input are available; otherwise no bytes are read and 0 is returned. It returns number of bytes read into the buffer or -1 if the end of file is reached.
  9. skip(long n): This method skips over and discards specified n bytes of data from the input stream and returns the actual number of bytes skipped. It throws an IOException if the specified n is negative.

5. Java FileInputStream Examples

Let’s look at some example programs for FileInputStream class.

5.1) Read File using FileInputStream


package com.journaldev.examples;

import java.io.File;
import java.io.FileInputStream;

/**
 * Java Read file using FileInputStream
 * 
 * @author pankaj
 *
 */
public class ReadFileUsingFileInputStream {

	public static void main(String[] args) {
		File file = null;
		FileInputStream fileInputStream = null;
		try {
			file = new File("D:/data/file.txt");
			fileInputStream = new FileInputStream(file);
			System.out.println("Available bytes in file: "+fileInputStream.available());
			int line;
			while ((line=fileInputStream.read()) != -1) {
				System.out.print((char)line);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
				if (fileInputStream != null) {
					fileInputStream.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}

	}

}

Output:


Available bytes in file: 48
Hello world.
This is a FileInputStream Program.

Note that file.txt is the file used in above program and its content is printed. You can create any other file and run this program by making the required changes.

Java 7 provides try with resource which is a try statement that declares one or more resource. A resource is an object that must be closed after the program is finished with it. The try with resource statement ensures that each resource is closed at the end of the statement.

Let’s have a look at the below example program using try with resources.


package com.journaldev.examples;

import java.io.File;
import java.io.FileInputStream;

/**
 * Java Read file using FileInputStream with Try with Resource
 * 
 * @author pankaj
 *
 */
public class FileInputStreamTryWithResource {

	public static void main(String[] args) {
		File file = new File("D:/data/file.txt");
		try (FileInputStream fileInputStream = new FileInputStream(file)){
			System.out.println("Available bytes in file: "+fileInputStream.available());
			int line;
			while ((line=fileInputStream.read()) != -1) {
				System.out.print((char)line);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

It will produce the same result as the earlier program. Also check java read text file for more about how to read text file in java.

5.2) finalize()

FileInputStream finalize() method ensures that the close() method of this file input stream is called when there are no more reference to it.

If we try to access FileInputStream after calling finalize(), we will get an exception.


package com.journaldev.examples;

import java.io.FileInputStream;
import java.io.FileNotFoundException;

/**
 * Java FileInputStream Finalize method example
 * 
 * @author pankaj
 *
 */
public class FileInputStreamFinalizeExample extends FileInputStream{

	public FileInputStreamFinalizeExample(String name) throws FileNotFoundException {
		super(name);
	}

	public static void main(String[] args) {
		FileInputStreamFinalizeExample file = null;
		try {
			file = new FileInputStreamFinalizeExample("D:/data/file.txt"); 
			System.out.println("Available bytes in the file: "+file.available());
			int line;
			while ((line=file.read()) != -1) {
				System.out.print((char)line);
			}
			//calling finalize method
			file.finalize();
			System.out.println("\n");
			System.out.println("------After finalize called--------");
			System.out.println(file.available());
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
				if (file != null) {
					file.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}

	}

}

The output of the above program is below:


Available bytes in the file: 48
Hello world.
This is a FileInputStream Program.

------After finalize called--------
java.io.IOException: Stream Closed
	at java.io.FileInputStream.available(Native Method)
	at com.journaldev.examples.FileInputStreamFinalizeExample.main(FileInputStreamFinalizeExample.java:31)

5.3) getFD()

FileInputStream getFD() returns the FileDescriptor object that represents the connection to the actual file in the file system being used by this FileInputStream. Let’s have look at the below example program.


package com.journaldev.examples;

import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;

/**
 * Java FileInputStream FileDescriptor Example
 * 
 * @author pankaj
 *
 */
public class FileInputStreamFileDescripterExample {

	public static void main(String[] args) {
		File file = new File("D:/data/file.txt");
		try (FileInputStream fileInputStream = new FileInputStream(file)){
			FileDescriptor fileDescriptor = fileInputStream.getFD();
			boolean valid = fileDescriptor.valid();
			System.out.println("Valid file: "+valid);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

Output of the above program is:


Valid file: true

5.4) read(byte[] b, int off, int len)

This method reads bytes of data up to specified length from this input stream into a specified array of bytes. If specified length is not zero, the method blocks until some input is available; otherwise, no bytes are read and 0 is returned. It returns the number of bytes read into the buffer or -1 if the end of file is reached.


package com.journaldev.examples;

import java.io.FileInputStream;

/**
 * Java Read file using read(byte[] b, int off, int len) method
 * 
 * @author pankaj
 *
 */
public class FileInputStreamRead {

	public static void main(String[] args) {
		try (FileInputStream fileInputStream = new FileInputStream("D:/data/file.txt")) {
			byte[] b = new byte[10];
			int i = fileInputStream.read(b, 0, 8);
			System.out.println("Available bytes in file: " + fileInputStream.available());
			System.out.println("Number of bytes in read from file: " + i);
			for (byte bs : b) {
				char c = (char) bs;
				if (bs == 0) {
					c = '-';
				}
				System.out.print(c);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

Output:


Available bytes in file: 40
Number of bytes in read from file: 8
Hello wo--

5.5) skip(long n)

FileInputStream skip(long n) method skips over and discards specified n bytes of data from the input stream and returns the actual number of bytes skipped. It throws an IOException if the specified n is negative.


package com.journaldev.examples;

import java.io.FileInputStream;

/**
 * Java Read file with skip(long n) method example
 * 
 * @author pankaj
 *
 */
public class FileInputStreamSkip {

	public static void main(String[] args) {
		try (FileInputStream fileInputStream = new FileInputStream("D:/data/file.txt")) {
			System.out.println("Available bytes in the file: " + fileInputStream.available());
			int line;
			//skip 2 bytes
			fileInputStream.skip(2);
			System.out.println("Available bytes in the file after skip: " + fileInputStream.available());
			while ((line=fileInputStream.read()) != -1) {
				System.out.print((char)line);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

The output of the above program is:


Available bytes in the file: 12
Available bytes in the file after skip: 10
llo world.

5.6) getChannel()

This method returns the unique FileChannel object associated with this file input stream. The initial position of the returned channel will be equal to the number of bytes read from the file and reading bytes from this stream will increment the channel’s position.


package com.journaldev.examples;

import java.io.FileInputStream;
import java.nio.channels.FileChannel;

/**
 * Java Read file with getChannel method example
 * 
 * @author pankaj
 *
 */
public class FileInputStreamChannel {

	public static void main(String[] args) {
		FileInputStream fileInputStream = null;
		FileChannel fileChannel = null;
		try {
			fileInputStream = new FileInputStream("D:/data/file.txt");
			System.out.println("Available bytes in file: " + fileInputStream.available());
			int line;
			while ((line=fileInputStream.read()) != -1) {
				fileChannel = fileInputStream.getChannel();
				System.out.print("No of bytes read: "+fileChannel.position());
	            System.out.println("; Char read: "+(char)line);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
				if (fileInputStream != null) {
					fileInputStream.close();
				}
				if (fileChannel != null) {
					fileChannel.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
	}

}

Output:


Available bytes in file: 12
No of bytes read: 1; Char read: H
No of bytes read: 2; Char read: e
No of bytes read: 3; Char read: l
No of bytes read: 4; Char read: l
No of bytes read: 5; Char read: o
No of bytes read: 6; Char read:  
No of bytes read: 7; Char read: w
No of bytes read: 8; Char read: o
No of bytes read: 9; Char read: r
No of bytes read: 10; Char read: l
No of bytes read: 11; Char read: d
No of bytes read: 12; Char read: .

That’s all for Java FileInputStream, I hope nothing important got missed here.

Reference: API Doc

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages