【问题标题】:Read filename from command line argument从命令行参数读取文件名
【发布时间】:2014-01-15 22:00:16
【问题描述】:

我的代码中有一个我正在阅读的文本文件的硬编码名称。

String fileName = "test.txt";

但是我现在必须像这样使用命令参数:

 text.java arg1 arg2 arg3 (can be any amount) < test.txt

谁能帮帮我?

我得到参数没问题,只是不确定文件。谢谢

我试过了:

String x = null;
        try {
            BufferedReader f = new BufferedReader(new InputStreamReader(System.in));

            while( (x = f.readLine()) != null )
            {
               System.out.println(x);
            }
        }
               catch (IOException e) {e.printStackTrace();}
               System.out.println(x);
              }

但是我的应用程序现在挂在 readLine 上,请问有什么想法可以尝试吗?

【问题讨论】:

  • 向我们展示如何获取参数(代码)。
  • 这样,您只将 test.txt 的内容传递给标准输入,而不是文件名。
  • @GaborBakos 啊,这更有意义,我编写了代码以根据名称阅读它。谢谢
  • @MariuszS 我用于 (int j = 0; j

标签: java


【解决方案1】:

这是因为文件不是传递作为参数,而是管道作为标准输入。

如果这是预期用途(通过管道传输文件的内容),那么您只需从System.in 读取它(in 表示标准输入):

public static void main(String[] args) throws IOException {
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    String firstLine = in.readLine();
    // etc.
}

如果你只是想传递文件名,那么你必须删除或转义 &lt;,因为它在 shell 中表示“管道”。

【讨论】:

  • 它似乎挂在 readLine 虽然没有错误,你知道它为什么会这样吗?
【解决方案2】:

将文件作为文件名传递给您的程序,然后打开该文件并从中读取。

【讨论】:

    最近更新 更多