【问题标题】:How to reach the input file using java program < "filename"?如何使用java程序<“文件名”访问输入文件?
【发布时间】:2015-01-28 23:25:12
【问题描述】:

我正在执行一项我应该处理文件的任务。测试人员使用命令参数

“java 谜题

用我的程序运行文件。我的程序是“拼图”,文件是“sample_input_1.txt”。

我一直在搜索,但我不太确定如何从该文件中检索数据。我习惯于将文件路径作为 main 的参数,我使用扫描仪来读取它。

在编程和检索数据时如何访问该文件?我想做一些类似于扫描仪读取它的事情。

谢谢各位!

【问题讨论】:

标签: java file-io input command-line arguments


【解决方案1】:

它在您的标准输入流中。澄清一下,如果你习惯使用 Scanner 的接受 File 的构造函数(像这样):

Scanner scanner = new Scanner(new File(args[0]));

然后使用接受 InputStream 的 Scanner 的构造函数,并传递 System.in:

Scanner scanner = new Scanner(System.in);

之后,您应该能够以您习惯的相同方式使用扫描仪。

【讨论】:

    【解决方案2】:

    它出现在标准输入流 ( System.in ) 中。命令末尾的&lt; sample_input_1.txt 将标准输入流重定向到给定文件。它几乎存在于每个终端程序中。更多信息可以在here找到。

    【讨论】:

      【解决方案3】:

      在我看来,最简单的方法是使用 InputStream

      try {
          BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
      
          String word;
          do {
          word = br.readLine();
          if (word != null) {
              list.add(word); //if you want add the file content to an ArrayList
          } else {
              return; //case file is empty, program is finished
          }
          } while (word != null);
      
      } catch (Exception e) {
          System.err.println("Error:" + e.getMessage());
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-10-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-07-26
        相关资源
        最近更新 更多