Java:使用Scanner类从文件中读取输入而不进行管道传输

时间:2022-08-16 21:51:05

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.

我目前有一个程序的实现,我使用Scanner类读入输入。整数整数。我通过命令行管道输入文件来做到这一点。

java program < input.txt

java程序

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

java程序--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.

或类似的东西。我知道我可以解析命令行参数,解压缩文本“input.txt”,然后使用类似“BufferedReader”或类似的类来读取文件。

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.

我只是好奇是否有使用输入文件(没有管道)并仍然使用Scanner类。这意味着我不必更改我的nextInt()和其他此类调用。

1 个解决方案

#1


1  

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.

由于参数只是没有被评估,而是传递给你的main(String [] args)方法而中间没有任何工作,你唯一的选择是解析参数,提取文件名input.txt并将其作为普通文件流打开。

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..

我不知道它应该如何推断文件必须打开并作为管道传递而不是管道..你可以轻松地使用带有File参数的Scanner而不需要任何麻烦。

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.

构造一个新的Scanner,它生成从指定文件扫描的值。使用底层平台的默认字符集将文件中的字节转换为字符。

#1


1  

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.

由于参数只是没有被评估,而是传递给你的main(String [] args)方法而中间没有任何工作,你唯一的选择是解析参数,提取文件名input.txt并将其作为普通文件流打开。

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..

我不知道它应该如何推断文件必须打开并作为管道传递而不是管道..你可以轻松地使用带有File参数的Scanner而不需要任何麻烦。

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.

构造一个新的Scanner,它生成从指定文件扫描的值。使用底层平台的默认字符集将文件中的字节转换为字符。