Read text file in Java using FileInputStream

Sharing is Caring

Recently I have seen some questions about reading a text file content on OTN forum, though it is very simple task still some find it confusing. That’s why here I am showing how to read text file in java using FileInputStream

This is a sample text file

Sample Text File

and here goes the java code to read text file using FileInputStream

package client;

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

public class ReadFileJava {
    public ReadFileJava() {
        super();
    }

    public static void main(String[] args) {
        // Absolute path of file that you want to read
        File f = new File("D:/sampleFile.txt");
        FileInputStream fis = null;

        try {
            fis = new FileInputStream(f);

            int data;
            //Iterate over file content
            while ((data = fis.read()) != -1) {
                System.out.print((char) data);
            }

        } catch (IOException ioe) {
            ioe.printStackTrace();
        } finally {
            try {
                if (fis != null)
                    fis.close();
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
    }
}

Run this code

And output is

Read text file in Java using FileInputStream

Cheers 🙂 Happy Learning

Related Posts

An Oracle ACE, Blogger, Reviewer, Technical Lead working on Oracle ADF

2 thoughts on “Read text file in Java using FileInputStream”

  1. Hello Ashish,

    Thanks for this wonderful post. I am using jdev 12.1.3 and have a similar requirement in adf to read file present in unix server path like “u03/prnqoc01/appl/common/attachment”
    Will providing this pathname work in reading the file?

    Regards,
    Abhik Dey

Leave a Reply

Your email address will not be published. Required fields are marked *