how to read file from console in java

‮th‬tps://www.lautturi.com
how to read file from console in java

To read a file from the console in Java, you can use the Scanner class, which provides a convenient way to read input from the console, a file, or any other input source.

Here is an example of how you can use the Scanner class to read a file from the console in Java:

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

public class FileReader {
    public static void main(String[] args) throws FileNotFoundException {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter the file name: ");
        String fileName = scanner.nextLine();
        File file = new File(fileName);
        scanner = new Scanner(file);

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

        scanner.close();
    }
}

In this example, the main method starts by creating a Scanner object that reads from the console using the System.in object. It then prompts the user to enter the file name and reads the file name using the nextLine method.

The main method then creates a File object using the file name and creates a new Scanner object that reads from the file using the File object.

The main method then reads the file line by line using the hasNextLine and nextLine methods of the Scanner class and prints each line to the console using the System.out.println method.

Finally, the Scanner object is closed using the close method.

This code will read the file from the console and print its contents to the console. You can modify the code to perform other operations with the file, such as parsing it or storing it in a data structure.

Keep in mind that this is just one way to read a file from the console in Java. You can use different techniques and libraries to achieve the same result, such as using the BufferedReader class or the FileReader class. You may also need to handle exceptions and other error conditions.

Created Time:2017-11-01 20:42:59  Author:lautturi