简体   繁体   中英

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?

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):

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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