简体   繁体   English

从命令行参数读取文件名

[英]Read filename from command line argument

I have in my code a hardcoded name for a text file I am reading. 我的代码中有一个我正在读取的文本文件的硬编码名称。

String fileName = "test.txt";

However I now have to use a command argument like so: 但是,我现在必须像这样使用命令参数:

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

Can anyone help me please? 谁能帮我吗?

I have it getting the arguments no problem just not sure on the file. 我有它得到的论据没问题只是不确定在文件上。 Thank you 谢谢

I have tried: 我努力了:

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);
              }

However my application now hangs on readLine, any ideas for me to try please? 但是我的应用程序现在挂在readLine上,请问有什么想法可以尝试吗?

That is because the file is not passed as an argument, but piped as standard input. 那是因为文件没有作为参数传递 ,而是通过管道作为标准输入传递

If that is the intended use (to pipe the content of the file), then you just have to read it from System.in ( in means standard input): 如果是这样的用途(管道文件的内容 ),那么你只需要读取它System.inin均值的标准输入):

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

If you just wanted to pass the file name, then you have to remove or escape that < , because it means "pipe" in shell. 如果您只想传递文件名,则必须删除或转义< ,因为它在shell中表示“管道”。

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

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

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