简体   繁体   English

用户输入文件控制台/命令行 - Java

[英]User Input File Console/Command Line - Java

Most examples out there on the web for inputting a file in Java refer to a fixed path: web 上用于在 Java 中输入文件的大多数示例指的是固定路径:

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.获得文件后,我可以转换为字符串等...我认为它与 BufferedReader、Scanner、FileInputStream、DataInputStream 等有关...我只是不确定如何将这些结合使用获得最有效的方法。

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使用 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.并用您的数据处理填充 while 循环。

Regards, Stéphane问候, 斯蒂芬

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM