ADVERTISEMENT
ADVERTISEMENT

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 »


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.