How do I read file using FileInputStream?

The following example use the class to read contents of a text file. We’ll read a file located in the temporary directory defined by operating system. This temporary directory can be accessed using the system property.



public class FileInputStreamDemo {
    public static void main(String[] args) {
        // Get the temporary directory. We'll read the data.txt file
        // from this directory.
        String tempDir = System.getProperty("");
        File file = new File(tempDir + "/data.txt");

        StringBuilder builder = new StringBuilder();
        FileInputStream fis = null;
        try {
            // Create a FileInputStream to read the file.
            fis = new FileInputStream(file);

            int data;
            // Read the entire file data. When -1 is returned it
            // means no more content to read.
            while ((data = != -1) {
                builder.append((char) data);
        } catch (IOException e) {
        } finally {
            if (fis != null) {
                try {
                } catch (IOException e) {

        // Print the content of the file
        System.out.println("File Contents = " + builder.toString());

The content read from the input stream will be appended into a StringBuilder object. At the end of the snippet the content of the will be converted into string using the toString() method.

Here are the content of our data.txt file.

File Contents = Lorem Ipsum is simply dummy text of the printing and typesetting industry.
Lorem Ipsum has been the industry's standard dummy text ever since the
1500s, when an unknown printer took a galley of type and scrambled it to
make a type specimen book. It has survived not only five centuries, but
also the leap into electronic typesetting, remaining essentially unchanged.
It was popularised in the 1960s with the release of Letraset sheets
containing Lorem Ipsum passages, and more recently with desktop publishing
software like Aldus PageMaker including versions of Lorem Ipsum.

Leave a Reply

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