从命令行参数读取文件名

时间:2014-01-15 22:00:17

标签: java

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

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上,有什么想法让我试试吗?

2 个答案:

答案 0 :(得分:2)

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

如果这是预期用途(用于管道文件的内容),则只需从System.inin表示标准输入)读取它:

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

如果你只想传递文件名,那么你必须删除或转义<,因为它在shell中意味着“管道”。

答案 1 :(得分:0)

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

相关问题