Q:

Java program to read a file line by line

0

Given a file and we have to read its content line by line using java program.

For this program, I am using a file named "B.txt" which is located at "E:\" drive, hence the path of the file is "E:\B.txt", and the content of the file is:

    This is line 1
    This is line 2
    This is line 3
    This is line 4

 

All Answers

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

Program to read file line by line in java

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Scanner;

public class ReadLineByLine {
  public static void main(String[] args) {
    // create object of scanner class.
    Scanner Sc = new Scanner(System.in);

    // enter file name.
    System.out.print("Enter the file name:");
    String sfilename = Sc.next();
    Scanner Sc1 = null;
    FileInputStream fis = null;
    try {
      FileInputStream FI = new FileInputStream(sfilename);
      Sc1 = new Scanner(FI);

      // this will read data till the end of data.
      while (Sc1.hasNext()) {
        String data = Sc1.nextLine();

        // print the data.
        System.out.print("The file data is : " + data);
      }
    } catch (IOException e) {
      System.out.println(e);
    }
  }

Output

Enter the file name: E:/B.txt
This is line 1
This is line 2
This is line 3
This is line 4

 

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

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now