Q:

Java program to read content from file using FileInputStream

belongs to collection: Java File Handling Programs

0

This program will read the content of the file using FileInputStream classFileInputStream 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.

 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java File Handling Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Java program to write content into file using Buff... >>
<< Java program to write content into file using File...