简体   繁体   English

Java:使用Scanner类无需管道即可从文件读取输入

[英]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. 我目前有一个程序的实现,可以使用Scanner类读取输入。 Integer by integer. 整数整数。 I do this by piping the input file via the command line. 我通过命令行输入文件来做到这一点。

java program < input.txt Java程序<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 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. 我只是很好奇是否可以使用输入文件(无管道)并且仍然使用Scanner类。 Which means I wouldn't have to change over my nextInt() and other such calls. 这意味着我将不必更改nextInt()和其他此类调用。

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.. 我看不到如何推断出文件必须作为管道打开并作为管道传递而不是管道..您可以轻松地将ScannerFile参数一起使用,而无需担心任何事情。

public Scanner(File source) throws FileNotFoundException

Constructs a new Scanner that produces values scanned from the specified file. 构造一个新的Scanner,该扫描仪生成从指定文件扫描的值。 Bytes from the file are converted into characters using the underlying platform's default charset. 使用基础平台的默认字符集将文件中的字节转换为字符。

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

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