In this section, you will learn how to read a file line by line.
In this section, you will learn how to read a file line by line.In this section, you will learn how to read a file line by line.
Java has provide several classes for file manipulation. Here we are going to
read a file line by line. For reading text from a file it's better to use a
Reader class instead of a InputStream class since Reader classes have the
purpose of reading textual input.
In the given example, we have simply create a BufferedReader object and start
reading from the file line by line until the readLine() method of BufferedReader
class returns null, which indicates the end of the file.
hello.txt:
Hello, Where there is will, there is a way. |
Here is the code:
import java.io.*; public class ReadFile { public static void main(String[] args) throws Exception { File f = new File("C:/Hello.txt"); if (!f.exists() && f.length() < 0) { System.out.println("The specified file does not exist"); } else { FileReader fr = new FileReader(f); BufferedReader reader = new BufferedReader(fr); String st = ""; while ((st = reader.readLine()) != null) { System.out.println(st); } } } }
In this above code, the BufferedReader class is used to read text from a file line by line using it's readLine method.