mydomain
No ADS
No ADS

Java FileInputStream Tutorial with Examples

  1. FileInputStream
  2. Example 1

1. FileInputStream

No ADS
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

No ADS
As a first example, we use FileInputStream to read a Japanese text file encoded with UTF-8:
utf8-file-without-bom.txt
JP日本-八洲
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.
FileInputStreamEx1.java
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);
        }
        fis.close();
    }
}
Output:
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:
No ADS

Java IO Tutorials

Show More
No ADS