【问题标题】:Reading from arguments files to process从参数文件中读取以进行处理
【发布时间】:2015-11-22 11:31:13
【问题描述】:

我在从命令行读取文件时遇到了一些问题。 我以前从未使用过命令行参数,所以我想我有点迷路了。 到目前为止,这是我正在尝试的:

FileInputStream fin1 = null;
for (int i = 0; i < args.length; i++) //command line argument for file input
{
    fin1 = new FileInputStream(args[i]);
}
//Scanner scan = new Scanner(fiin1);

我已经注释掉了我的扫描仪,因为我使用了不同的方法(我将 fin1 作为参数传入其中)并且该方法中有一个扫描仪。但是,我不太确定我是否仍然需要那里的扫描仪(也许作为参数传递给其他方法)。

无论如何,如果我运行我的代码,我会得到一个 NullPointerException,我认为这是因为我将 FileInputStream 初始化为 null。但是如果我在 for 循环中改变它,那有什么关系呢? 另外,我需要保持我的 main 方法原样,以便我可以在其中做更多事情。

谁能帮忙?

【问题讨论】:

  • 您正在分配使用传递给程序的最后一个参数创建的 FileInputStream。在我看来,您可能根本没有传递任何参数,因此 for 循环中的语句永远不会执行。请使用您传递给程序的参数更新问题。

标签: java command-line-arguments fileinputstream


【解决方案1】:

注意它被称为 FileInputStream ,所以我们需要使用 File 。

您可以简单地使用 Scanner ,并将其设置为 System.in

            Scanner scanner = new Scanner(System.in);

然后,你可以初始化那个FileInputStream

How to Read Strings from Scanner in console Application JAVA?

【讨论】:

    【解决方案2】:

    使用以下代码。

        if (args.length < 1) {
            System.out.println("No file was given as an argument..!");
            System.exit(1);
        }
        String fileName = args[0];
        Scanner scanner = new Scanner(new File(fileName));
    

    如果您想使用FileInputStream,则更改最后一行以创建FileInputStream 实例。

       fin1 = new FileInputStream(fileName);
    

    如果您只提供一个文件名作为参数,则无需使用for-loop。您可以按如下方式运行您的代码。

    javac MyClass.java       //Compile your code(Assumed that your file is MyClass.java
    java MyClass filename    //Change filename with the path to your file
    

    您得到NullPointerException 可能是因为您在运行java 代码时没有使用文件名作为参数。

    【讨论】:

      【解决方案3】:

      首先:当您运行代码时,您只会到达最后一个参数。 你应该这样做:

       FileInputStream fileInputStream = null;
          for (String argument : args) {
              fileInputStream = new FileInputStream(argument);
              //you should process your argument in block together with creating fis
              Scanner scanner = new Scanner(fileInputStream);
              //now, when a scanner copy is created, you can use it (or you can use your own
              while (scanner.hasNext()) {
                  System.out.println(scanner.nextLine());
              }
          }
      

      【讨论】:

        猜你喜欢
        • 2018-07-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-07-29
        • 1970-01-01
        • 2021-07-29
        • 1970-01-01
        • 2020-11-12
        相关资源
        最近更新 更多