Java File Operation Reading a file whose name we get from the user in console input

I have to get the name of a file, say, A.txt from user in console and open the file and read it(to be more specific, tokenize it). How can I do it? I am not able to get the filename from the reader and open it with filename.txt.

Here's the code snippet:

    String file = args[0];
    BufferedReader reader = new BufferedReader(new FileReader(file));
Jon Skeet
people
quotationmark

args[0] will refer to the first command line argument, e.g.

java Foo filename.txt

If you want it on the interactive console, i.e. after the program has started, you should use System.in, e.g.

BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String filename = reader.readLine();

(As an aside, I'd recommend against using FileReader - it always uses the platform default encoding. I'd suggest either using FileInputStream wrapped in InputStreamReader, or just use Files.newBufferedReader which defaults to UTF-8 but has an overload to allow you to specify the encoding.)

people

See more on this question at Stackoverflow