开发者

User Input File Console/Command Line - Java

开发者 https://www.devze.com 2023-03-11 05:49 出处:网络
Most examples out there on the web for inputting a file in Java refer to a fixed path: File file = new File(\"myfile.txt\");

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开发者_StackOverflow中文版'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.


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);


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

0

精彩评论

暂无评论...
验证码 换一张
取 消