java scan a file 1

java scan a file

import java.io.File;
import java.util.Scanner;

public class ReadFile {

    public static void main(String[] args) {

        try {
            System.out.print("Enter the file name with extension : ");

            Scanner input = new Scanner(System.in);

            File file = new File(input.nextLine());

            input = new Scanner(file);


            while (input.hasNextLine()) {
                String line = input.nextLine();
                System.out.println(line);
            }
            input.close();

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

}

Here is what the above code is Doing:
1. We are asking the user to enter the file name with extension.
2. We are creating a File object and passing the file name to its constructor.
3. We are creating a Scanner object and passing the file object to its constructor.
4. We are using the hasNextLine() method of the Scanner class to check if there is another line present in the file or not.
5. If there is another line present in the file, we are using the nextLine() method of the Scanner class to read the line.
6. We are printing the line on the console.
7. We are closing the Scanner object.
8. We are handling the IOException by printing the stack trace of the exception.

Similar Posts