Java FileInputStream Tutorial with Examples

View more Tutorials:

Follow us on our fanpages to receive notifications every time there are new articles. Facebook Twitter

1- FileInputStream

FileInputStream is a subclass of InputStream, which is used to read binary files such as photos, music, video. Received data of the reading is raw bytes. For regular text files you should use FileReader instead.

public class FileInputStream extends InputStream  
FileInputStream constructors

FileInputStream​(File file)  

FileInputStream​(FileDescriptor fdObj)     

FileInputStream​(String name)
Most of FileInputStream methods are inherited from InputStream:

public final FileDescriptor getFD() throws IOException  
public FileChannel getChannel()  

// Methods inherited from InputStream:

public int read() throws IOException   
public int read(byte b[]) throws IOException    
public int read(byte b[], int off, int len) throws IOException  
public byte[] readAllBytes() throws IOException   
public byte[] readNBytes(int len) throws IOException  
public int readNBytes(byte[] b, int off, int len) throws IOException
public long skip(long n) throws IOException  
public int available() throws IOException   

public synchronized void mark(int readlimit)  
public boolean markSupported()  

public synchronized void reset() throws IOException
public void close() throws IOException  

public long transferTo(OutputStream out) throws IOException
FileChannel getChannel() It is used to return the unique FileChannel object associated with this FileInputStream.
FileDescriptor getFD() It is used to return the FileDescriptor object.

2- Example 1

As a first example, we use FileInputStream to read a Japanese text file encoded with UTF-8:

Note: UTF-8 uses 1, 2, 3 or 4 bytes to store one character. Meanwhile, FileInputStream reads each byte from the file so you'll get a pretty strange result.

package org.o7planning.fileinputstream.ex;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.MalformedURLException;

public class FileInputStreamEx1 {

    public static void main(String[] args) throws MalformedURLException, IOException {
        // Windows Path:  C:/Data/test/utf8-file-without-bom.txt
        String path = "/Volumes/Data/test/utf8-file-without-bom.txt";
        File file = new File(path);
        FileInputStream fis = new FileInputStream(file);
        int code;
        while((code = fis.read()) != -1) {
            char ch = (char) code;
            System.out.println(code + "  " + ch);

74  J
80  P
230  æ
151  —
165  ¥
230  æ
156  œ
172  ¬
45  -
229  å
133  …
171  «
230  æ
180  ´
178  ²
To read text files UTF-8, UTF-16, ... you should use FileReader or InputStreamReader:

View more Tutorials: