FileInputStream

java.io.FileInputStream – Java FileInputStream Example

In this example, we are going to see how to use FileInputStream in Java and inputstream. FileInputStream in an InputStream 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 with InputStream, a FileInputStream 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 the FileInputStream around a suitable Reader class.

1. Reading bytes from a file

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

1.1 Read a single byte

You can use read() method of FileInputStream 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
package com.javacodegeeks.core.io.inputstream;
 
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
 
public class FileInputStreamExample {
 
    public static final String INPUT_FILE="F:\\nikos7\\Desktop\\testFiles\\textFile.txt";
 
    public static void main(String[] args){
 
        try ( InputStream inputStream = new FileInputStream(INPUT_FILE) ) {
 
            System.out.println("Available bytes from the file :"+inputStream.available());
 
            // read a single byte
            int b = inputStream.read();
 
            System.out.println("Read byte : +"+b);
 
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }  
}

This will output:

Available bytes from the file :183500798
Read 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 use int read(byte[] buff) and int 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
package com.javacodegeeks.core.io.inputstream;
 
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
 
public class FileInputStreamExample {
 
    public static final String INPUT_FILE="F:\\nikos7\\Desktop\\testFiles\\textFile.txt";
 
    public static void main(String[] args){
 
        byte[] bytes = new byte[100];
 
        try ( InputStream inputStream = new FileInputStream(INPUT_FILE) ) {
 
            System.out.println("Available bytes from the file :"+inputStream.available());
 
            int bytesread = 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 will output:

Available bytes from the file :183500798
Read 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 use int 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
package com.javacodegeeks.core.io.inputstream;
 
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
 
public class FileInputStreamExample {
 
    public static final String INPUT_FILE="F:\\nikos7\\Desktop\\testFiles\\textFile.txt";
 
    public static void main(String[] args){
 
        byte[] bytes = new byte[100];
 
        try ( InputStream inputStream = new FileInputStream(INPUT_FILE) ) {
 
            System.out.println("Available bytes from the file :"+inputStream.available());
 
            int bytesread = 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 will output:

Available bytes from the file :183500798
Read 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 the FileInputStream. For that, you can use a BufferedInputStream. 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 a BufferedInputStream is no different from using a FileInputStream, or in fact, an InputStream, 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
package com.javacodegeeks.core.io.inputstream;
 
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
 
public class FileInputStreamExample {
 
    public static final String INPUT_FILE="F:\\nikos7\\Desktop\\testFiles\\textFile.txt";
 
    public static void main(String[] args){
 
        byte[] bytes = new byte[100];
 
        try ( InputStream inputStream = new BufferedInputStream (new FileInputStream(INPUT_FILE),1024) ) {
 
            System.out.println("Available bytes from the file :"+inputStream.available());
 
            int bytesread = 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 will output:

Available bytes from the file :183500798
Read 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 use BufferedInputStream.I’ve also specified the size of the internal buffer to be 1024 bytes in the constructor of BufferedInputStream.

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
package com.javacodegeeks.core.io.inputstream;
 
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
 
public class FileInputStreamExample {
 
    public static final String INPUT_FILE="F:\\nikos7\\Desktop\\testFiles\\textFile.txt";
 
    public static void main(String[] args){
 
        char[] chars = new char[50];
 
        try ( InputStreamReader inputStreamReader = new InputStreamReader (new FileInputStream(INPUT_FILE)) ) {
 
            int charsread = 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 will output:

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 convenient FileReader class that opens up a character stream directly without having to create a FileInputStream and then an InputStreamReader. Of course, you can also buffer an java inputstream using an BufferedReader. 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
package com.javacodegeeks.core.io.inputstream;
 
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
 
public class FileInputStreamExample {
 
    public static final String INPUT_FILE="F:\\nikos7\\Desktop\\testFiles\\textFile.txt";
 
    public static void main(String[] args){
 
        String line="";
 
        try ( BufferedReader bufferedReader = new BufferedReader (new  InputStreamReader (new FileInputStream(INPUT_FILE))) ) {
 
            while  ( ( line =bufferedReader.readLine()) !=null ){
                System.out.println(line);
            }
 
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }
}

This will output:

sdvojpojvpaosjdpvjpoasjdv
asjdvojpaosjdpvjpaosjdvasdv
aosdbfpjaosjdobjaspodbj
opaposjcdoasdvopasdv
asdvopasodjvopjapsov[asdv
poasdvpojasdv[askdv[pk[
sadvpsojdvojspodvj
sdvojpojvpaosjdpvjpoasjdv
asjdvojpaosjdpvjpaosjdvasdv
aosdbfpjaosjdobjaspodbj
...

3. FileInputStream and NIO

You can also use the Files NIO class to obtain a FileInputStream.

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
package com.javacodegeeks.core.io.inputstream;
 
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
 
public class FileInputStreamExample {
 
public static final String INPUT_FILE="F:\\nikos7\\Desktop\\testFiles\\textFile.txt";
 
    public static void main(String[] args){
 
        Path filePath = Paths.get(INPUT_FILE);
 
        byte[] bytes = new byte[100];
 
        try ( InputStream inputStream = Files.newInputStream(filePath) ) {
 
            System.out.println("Available bytes from the file :"+inputStream.available());
 
            int bytesread = 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 will output:

Available bytes from the file :183500798
Read 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 a BufferedReader:

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
package com.javacodegeeks.core.io.inputstream;
 
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
 
public class FileInputStreamExample {
 
public static final String INPUT_FILE="F:\\nikos7\\Desktop\\testFiles\\textFile.txt";
 
    public static void main(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 will output:

sdvojpojvpaosjdpvjpoasjdv
asjdvojpaosjdpvjpaosjdvasdv
aosdbfpjaosjdobjaspodbj
opaposjcdoasdvopasdv
asdvopasodjvopjapsov[asdv
poasdvpojasdv[askdv[pk[
sadvpsojdvojspodvj
sdvojpojvpaosjdpvjpoasjdv
asjdvojpaosjdpvjpaosjdvasdv
aosdbfpjaosjdobjaspodbj
...

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

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button