Java – User Input File Console/Command Line – Java

consolefile-iojava

Most examples out there on the web for inputting a file in Java refer to a fixed path:

File file = new File("myfile.txt");

What about a user input file from the console? Let's say I want the user to enter a file:

System.out.println("Enter a file to read: ");

What options do I have (using as little code as possible) to read in a user specified file for processing. Once I have the file, I can convert to string, etc… I'm thinking it has to do with BufferedReader, Scanner, FileInputStream, DataInputStream, etc… I'm just not sure how to use these in conjunction to get the most efficient method.

I am a beginner, so I might well be missing something easy. But I have been messing with this for a while now to no avail.

Thanks in advance.

Best Answer

To have the user enter a file name, there are several possibilities:

As a command line argument.

public static void main(String[] args) {
  if (0 < args.length) {
    String filename = args[0];
    File file = new File(filename);
  }
}

By asking the user to type it in:

Scanner scanner = new Scanner(System.in);
System.out.print("Enter a file name: ");
System.out.flush();
String filename = scanner.nextLine();
File file = new File(filename);