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

发布于 2024-09-26 05:20:51 字数 377 浏览 2 评论 0原文

我目前有一个程序的实现,我使用 Scanner 类读取输入。整数乘整数。 我通过命令行通过管道传输输入文件来完成此操作。

java程序<输入.txt

我需要避免通过在命令行上使用参数来在程序中打开文件来管道输入。

java程序--file=input.txt

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

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

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

伤感在游骋 2024-10-03 05:20:51

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

我不明白它应该如何推断文件必须作为管道打开和传递而不是管道。您可以轻松地将 ScannerFile 参数一起使用,而无需为什么事烦恼..

public Scanner(File source) throws FileNotFoundException

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

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文