12

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.

nicorellius
  • 3,015
  • 4
  • 40
  • 74

2 Answers2

20

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);
nicorellius
  • 3,015
  • 4
  • 40
  • 74
Roland Illig
  • 37,193
  • 10
  • 75
  • 113
  • I don't think you need to flush in this case: http://stackoverflow.com/questions/7166328/when-why-to-call-system-out-flush-in-java – Hunter S Dec 06 '15 at 21:11
  • @HunterS: That other question mentions a few cases in which the `flush` is not necessary. The above code is not one of them, therefore I decided it would be better to be explicit about it. According to the [PrintStream](http://docs.oracle.com/javase/7/docs/api/java/io/PrintStream.html#write(int)) Javadoc it is necessary in this case, since the string does not contain a `\n` character. – Roland Illig Dec 12 '15 at 12:05
0

Use a java.io.BufferedReader

String readLine = "";
try {
      BufferedReader br = new BufferedReader(new FileReader( <the filename> ));
      while ((readLine = br.readLine()) != null) { 
        System.out.println(readLine);
      } // end while 
    } // end try
    catch (IOException e) {
      System.err.println("Error Happened: " + e);
    }

And fill the while loop with your data processing.

Regards, Stéphane

Snicolas
  • 36,854
  • 14
  • 106
  • 172