简体   繁体   中英

Java: Using the Scanner class to read input from a file without pipeing

I currently have an implementation of a program where I read in the input using the Scanner class. Integer by integer. I do this by piping the input file via the command line.

java program < input.txt

I need to avoid piping the input by using an argument on the command line to open the file in my program.

java program --file=input.txt

or something similar. I understand that I could parse the command line argument, extract the text "input.txt" and then use a class like "BufferedReader" or something similar to read the file.

I am just curious if there is away to use the input file (no piping) AND still use the Scanner class. Which means I wouldn't have to change over my nextInt() and other such calls.

Since arguments are just not evaulated but passed to your main(String[] args) method without any work in the middle your only option is to parse the argument, extract the filename input.txt and open it as a normal file stream.

I wouldn't see how it should infer that a file must be opened and passed as a pipe without being a pipe.. you can easily use Scanner with a File argument without bothering about anything..

public Scanner(File source) throws FileNotFoundException

Constructs a new Scanner that produces values scanned from the specified file. Bytes from the file are converted into characters using the underlying platform's default charset.

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