To read file in java we need to use java.io package. File class is used to get path of a file at specific path. FileInputStream class get file stream by opening file and get bytes stream and convert into character stream. In java we can use BufferedReader to read character input stream which create by InputStreamReader class. readLine() method is used to read file by line by line and write the content in our string variable.
Example will explain how to read content text a file in java
import java.io.File; import java.io.FileInputStream; import java.io.BufferedReader; import java.io.InputStreamReader; public class JavaIOReadFileExample { public static void main(String[] args) { File f=new File("c:\\readFileinJava.txt"); try { FileInputStream fs = new FileInputStream(f); InputStreamReader in = new InputStreamReader(fs); BufferedReader br = new BufferedReader(in); String text; while(true) { text=br.readLine(); if(text==null) break; System.out.println(text); } } catch (Exception e) { e.printStackTrace(); } } }
Output
Text Content written in java file
Reading this text from text file
This example reads file line by line



Link to Us