FileInputStream

java.io.FileInputStream – Java FileInputStream Example

Photo of Nikos MaravitsasNikos MaravitsasApril 14th, 2014Last Updated: December 4th, 2020
0 299 9 minutes read

In this example, we are going to see how to use FileInputStream in Java and inputstream.FileInputStream in anInputStream subclass that is used to read data from files in a file system.

It is actually connected to a specific file and can be used to extract data from them and make them available inside your program for manipulation. As withInputStream, aFileInputStream is responsible for reading raw bytes from a source (in this case a file). If you want to read a text file in character format you have to wrap theFileInputStream around a suitableReader class.

1. Reading bytes from a file

Let’s see how you can obtain aFileInputStream and read bytes from a file.

1.1 Read a single byte

You can useread() method ofFileInputStream to read a single byte form the file.read() will return the byte in the form of a decimal integer with valu 0-255:

FileInputStreamExample.java

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
packagecom.javacodegeeks.core.io.inputstream;
 
importjava.io.FileInputStream;
importjava.io.FileNotFoundException;
importjava.io.IOException;
importjava.io.InputStream;
 
publicclassFileInputStreamExample {
 
    publicstaticfinalString INPUT_FILE="F:\\nikos7\\Desktop\\testFiles\\textFile.txt";
 
    publicstaticvoidmain(String[] args){
 
        try( InputStream inputStream =newFileInputStream(INPUT_FILE) ) {
 
            System.out.println("Available bytes from the file :"+inputStream.available());
 
            // read a single byte
            intb = inputStream.read();
 
            System.out.println("Read byte : +"+b);
 
        }catch(FileNotFoundException e) {
            e.printStackTrace();
        }catch(IOException e1) {
            e1.printStackTrace();
        }
    }  
}

This willoutput:

Available bytes from the file :183500798Read byte :111

As you can see, we’ve also demonstrated available() method. This method will return an estimate of how many bytes are available for the next reading method to read without blocking.

1.2 Read a sequence of bytes

Naturally reading a file byte by byte is a bit of a pain. That’s why you can useint read(byte[] buff) andint read(byte[] buff,int off, int len) methods to read a sequence of bytes from the file and store them in a byte array.

FileInputStreamExample.java

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
packagecom.javacodegeeks.core.io.inputstream;
 
importjava.io.FileInputStream;
importjava.io.FileNotFoundException;
importjava.io.IOException;
importjava.io.InputStream;
importjava.util.Arrays;
 
publicclassFileInputStreamExample {
 
    publicstaticfinalString INPUT_FILE="F:\\nikos7\\Desktop\\testFiles\\textFile.txt";
 
    publicstaticvoidmain(String[] args){
 
        byte[] bytes =newbyte[100];
 
        try( InputStream inputStream =newFileInputStream(INPUT_FILE) ) {
 
            System.out.println("Available bytes from the file :"+inputStream.available());
 
            intbytesread = inputStream.read(bytes);
 
            System.out.println("Read bytes :"+bytesread);
            System.out.println(Arrays.toString(bytes));
 
        }catch(FileNotFoundException e) {
            e.printStackTrace();
        }catch(IOException e1) {
            e1.printStackTrace();
        }
    }
}

This willoutput:

Available bytes from the file :183500798Read bytes :100[111, 112, 97, 112, 111, 115, 106, 99, 100, 111, 97, 115, 100, 118, 111, 112, 97, 115, 100, 118, 13, 10, 97, 115, 100, 118, 111, 112, 97, 115, 111, 100, 106, 118, 111, 112, 106, 97, 112, 115, 111, 118, 91, 97, 115, 100, 118, 13, 10, 112, 111, 97, 115, 100, 118, 112, 111, 106, 97, 115, 100, 118, 91, 97, 115, 107, 100, 118, 91, 112, 107, 91, 13, 10, 115, 97, 100, 118, 112, 115, 111, 106, 100, 118, 111, 106, 115, 112, 111, 100, 118, 106, 13, 10, 115, 100, 118, 111, 106, 112]

In this case, I’ve read a sequence of 100 bytes and stored them in a byte array.int read(byte[] buff) will attempt to read 100 bytes, the size of the array. But it is not guaranteed that it will certainly ready 100 bytes. That why the actual number of bytes it has read is returned as an integer. Let’s see how you can useint read(byte[] buff,int off, int len) to read a sequence of bytes and store them in an array of bytes. Here you can specify an offset that you want your bytes to be copied to, instead of just filling up your buffer from the beginning.

FileInputStreamExample.java

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
packagecom.javacodegeeks.core.io.inputstream;
 
importjava.io.FileInputStream;
importjava.io.FileNotFoundException;
importjava.io.IOException;
importjava.io.InputStream;
importjava.util.Arrays;
 
publicclassFileInputStreamExample {
 
    publicstaticfinalString INPUT_FILE="F:\\nikos7\\Desktop\\testFiles\\textFile.txt";
 
    publicstaticvoidmain(String[] args){
 
        byte[] bytes =newbyte[100];
 
        try( InputStream inputStream =newFileInputStream(INPUT_FILE) ) {
 
            System.out.println("Available bytes from the file :"+inputStream.available());
 
            intbytesread = inputStream.read(bytes,10,20);
 
            System.out.println("Read bytes :"+bytesread);
            System.out.println(Arrays.toString(bytes));
 
        }catch(FileNotFoundException e) {
            e.printStackTrace();
        }catch(IOException e1) {
            e1.printStackTrace();
        }
    }
}

This willoutput:

Available bytes from the file :183500798Read bytes :20[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 111, 112, 97, 112, 111, 115, 106, 99, 100, 111, 97, 115, 100, 118, 111, 112, 97, 115, 100, 118, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

You can also choose how many bytes you want to read. In the above example, I’ve chosen to read 20 bytes and I want them to be stored from the bytes[10] position of my array and so forth.

1.3 Buffering a FileInputStream

If your application is very I/O intensive and it intends to read large amounts of data from large files, then it’s highly advised to buffer theFileInputStream. For that, you can use aBufferedInputStream. This will automatically create an internal buffer and perform as less I/O operations as possible. You can also choose the internal buffer size.

Using aBufferedInputStream is no different from using aFileInputStream, or in fact, anInputStream, but it adds that extra internal buffering that can make a difference in performance in many applications. Let’s see how you can use it:

FileInputStreamExample.java

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
packagecom.javacodegeeks.core.io.inputstream;
 
importjava.io.BufferedInputStream;
importjava.io.FileInputStream;
importjava.io.FileNotFoundException;
importjava.io.IOException;
importjava.io.InputStream;
importjava.util.Arrays;
 
publicclassFileInputStreamExample {
 
    publicstaticfinalString INPUT_FILE="F:\\nikos7\\Desktop\\testFiles\\textFile.txt";
 
    publicstaticvoidmain(String[] args){
 
        byte[] bytes =newbyte[100];
 
        try( InputStream inputStream =newBufferedInputStream (newFileInputStream(INPUT_FILE),1024) ) {
 
            System.out.println("Available bytes from the file :"+inputStream.available());
 
            intbytesread = inputStream.read(bytes,10,20);
 
            System.out.println("Read bytes :"+bytesread);
            System.out.println(Arrays.toString(bytes));
 
        }catch(FileNotFoundException e) {
            e.printStackTrace();
        }catch(IOException e1) {
            e1.printStackTrace();
        }
    }
}

This willoutput:

Available bytes from the file :183500798Read bytes :20[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 111, 112, 97, 112, 111, 115, 106, 99, 100, 111, 97, 115, 100, 118, 111, 112, 97, 115, 100, 118, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

You can see that there is no difference in the way you useBufferedInputStream.I’ve also specified the size of the internal buffer to be 1024 bytes in the constructor ofBufferedInputStream.

2. Reading characters from a file

When dealing with binary files, reading bytes is normally fine. But is not very convenient when you read text files. That’s why Java offers special Reader classes that wrap around a byte stream and convert it to a character stream. You can also specify the character set encoding that you want. In our case, we are going to use an java inputstream .

Let’s see how you can use it to read characters from a file.

FileInputStreamExample.java

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
packagecom.javacodegeeks.core.io.inputstream;
 
importjava.io.FileInputStream;
importjava.io.FileNotFoundException;
importjava.io.IOException;
importjava.io.InputStreamReader;
importjava.util.Arrays;
 
publicclassFileInputStreamExample {
 
    publicstaticfinalString INPUT_FILE="F:\\nikos7\\Desktop\\testFiles\\textFile.txt";
 
    publicstaticvoidmain(String[] args){
 
        char[] chars =newchar[50];
 
        try( InputStreamReader inputStreamReader =newInputStreamReader (newFileInputStream(INPUT_FILE)) ) {
 
            intcharsread = inputStreamReader.read(chars,0,20);
 
            System.out.println("Read characters :"+charsread);
            System.out.println(Arrays.toString(chars));
 
        }catch(FileNotFoundException e) {
            e.printStackTrace();
        }catch(IOException e1) {
            e1.printStackTrace();
        }
    }
}

This willoutput:

Read characters :20

[o, p, a, p, o, s, j, c, d, o, a, s, d, v, o, p, a, s, d, v, , , , , , , , , , , , , , , , , , ]

Java offers a convenientFileReader class that opens up a character stream directly without having to create aFileInputStream and then anInputStreamReader. Of course, you can also buffer an java inputstream using anBufferedReader.BufferedReader offers a very convenient readLine method that enables to read character streams line by line. Let’s see how:

FileInputStreamExample.java

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
packagecom.javacodegeeks.core.io.inputstream;
 
importjava.io.BufferedReader;
importjava.io.FileInputStream;
importjava.io.FileNotFoundException;
importjava.io.IOException;
importjava.io.InputStreamReader;
 
publicclassFileInputStreamExample {
 
    publicstaticfinalString INPUT_FILE="F:\\nikos7\\Desktop\\testFiles\\textFile.txt";
 
    publicstaticvoidmain(String[] args){
 
        String line="";
 
        try( BufferedReader bufferedReader =newBufferedReader (new InputStreamReader (newFileInputStream(INPUT_FILE))) ) {
 
            while ( ( line =bufferedReader.readLine()) !=null){
                System.out.println(line);
            }
 
        }catch(FileNotFoundException e) {
            e.printStackTrace();
        }catch(IOException e1) {
            e1.printStackTrace();
        }
    }
}

This willoutput:

sdvojpojvpaosjdpvjpoasjdvasjdvojpaosjdpvjpaosjdvasdvaosdbfpjaosjdobjaspodbjopaposjcdoasdvopasdvasdvopasodjvopjapsov[asdvpoasdvpojasdv[askdv[pk[sadvpsojdvojspodvjsdvojpojvpaosjdpvjpoasjdvasjdvojpaosjdpvjpaosjdvasdvaosdbfpjaosjdobjaspodbj...

3. FileInputStream and NIO

You can also use theFiles NIO class to obtain aFileInputStream.

FileInputStreamExample.java

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
packagecom.javacodegeeks.core.io.inputstream;
 
importjava.io.FileNotFoundException;
importjava.io.IOException;
importjava.io.InputStream;
importjava.nio.file.Files;
importjava.nio.file.Path;
importjava.nio.file.Paths;
importjava.util.Arrays;
 
publicclassFileInputStreamExample {
 
publicstaticfinalString INPUT_FILE="F:\\nikos7\\Desktop\\testFiles\\textFile.txt";
 
    publicstaticvoidmain(String[] args){
 
        Path filePath = Paths.get(INPUT_FILE);
 
        byte[] bytes =newbyte[100];
 
        try( InputStream inputStream = Files.newInputStream(filePath) ) {
 
            System.out.println("Available bytes from the file :"+inputStream.available());
 
            intbytesread = inputStream.read(bytes,10,20);
 
            System.out.println("Read bytes :"+bytesread);
            System.out.println(Arrays.toString(bytes));
 
        }catch(FileNotFoundException e) {
            e.printStackTrace();
        }catch(IOException e1) {
            e1.printStackTrace();
        }
    }
}

This willoutput:

Available bytes from the file :183500798Read bytes :20[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 111, 112, 97, 112, 111, 115, 106, 99, 100, 111, 97, 115, 100, 118, 111, 112, 97, 115, 100, 118, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

Or you can obtain directly aBufferedReader:

FileInputStreamExample.java

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
packagecom.javacodegeeks.core.io.inputstream;
 
importjava.io.BufferedReader;
importjava.io.FileNotFoundException;
importjava.io.IOException;
importjava.nio.charset.Charset;
importjava.nio.file.Files;
importjava.nio.file.Path;
importjava.nio.file.Paths;
 
publicclassFileInputStreamExample {
 
publicstaticfinalString INPUT_FILE="F:\\nikos7\\Desktop\\testFiles\\textFile.txt";
 
    publicstaticvoidmain(String[] args){
 
        Path filePath = Paths.get(INPUT_FILE);
 
        String line ="";
 
        try( BufferedReader bufferedReader = Files.newBufferedReader(filePath,Charset.defaultCharset()) ) {
 
            while ( ( line =bufferedReader.readLine()) !=null){
                System.out.println(line);
            }
 
        }catch(FileNotFoundException e) {
            e.printStackTrace();
        }catch(IOException e1) {
            e1.printStackTrace();
        }
    }
}

This willoutput:

sdvojpojvpaosjdpvjpoasjdvasjdvojpaosjdpvjpaosjdvasdvaosdbfpjaosjdobjaspodbjopaposjcdoasdvopasdvasdvopasodjvopjapsov[asdvpoasdvpojasdv[askdv[pk[sadvpsojdvojspodvjsdvojpojvpaosjdpvjpoasjdvasjdvojpaosjdpvjpaosjdvasdvaosdbfpjaosjdobjaspodbj...

4. Download the source code

This was a Java FileInputStream Example and inputstream.

Download
You can download the source code of this example here:java.io.FileInputStream – Java FileInputStream Example

Last updated on May 19th, 2020

Do you want to know how to develop your skillset to become aJava Rockstar?
Subscribe to our newsletter to start Rockingright now!
To get you started we give you our best selling eBooks forFREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to theTerms andPrivacy Policy

Thank you!

We will contact you soon.

Photo of Nikos MaravitsasNikos MaravitsasApril 14th, 2014Last Updated: December 4th, 2020
0 299 9 minutes read
Photo of Nikos Maravitsas

Nikos Maravitsas

Nikos has graduated from the Department of Informatics and Telecommunications of The National and Kapodistrian University of Athens. During his studies he discovered his interests about software development and he has successfully completed numerous assignments in a variety of fields. Currently, his main interests are system’s security, parallel systems, artificial intelligence, operating systems, system programming, telecommunications, web applications, human – machine interaction and mobile development.
Subscribe
Notify of
guest
I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.

I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.