Java program to read content from file using FileInputStream

This program will read the content of the file using FileInputStream class. FileInputStream class provide the methods for file input related operations. This program is using FileInputStream.read() method which returns an integer value and them we are converting it into character. We will read values until -1 is not found. This is an example of File Handling in Java.

Read Content from File using FileInputStream in Java

// Java program to read content from file 
// using FileInputStream

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

public class ReadFile {
  public static void main(String args[]) {
    final String fileName = "file1.txt";

    try {
      File objFile = new File(fileName);
      if (objFile.exists() == false) {
        System.out.println("File does not exist!!!");
        System.exit(0);
      }

      //reading content from file
      String text;
      int val;

      //object of FileOutputStream
      FileInputStream fileIn = new FileInputStream(objFile);
      //read text from file
      System.out.println("Content of the file is: ");
      while ((val = fileIn.read()) != -1) {
        System.out.print((char) val);
      }

      System.out.println();

      fileIn.close();
    } catch (Exception Ex) {
      System.out.println("Exception : " + Ex.toString());
    }
  }
}

Output

    
Content of the file is: 
Java is a platform independent language.

Java File Handling Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.