[英]How to input a text file into a java program via terminal (like how it's done in C++)?
If i do如果我做
$ java ProgramName string1 string2 string3
from the linux terminal, ProgramName gets string1 string2 string3 via main(String arg[])
using arg[i]
, and all is well.从 linux 终端,ProgramName 使用
arg[i]
通过main(String arg[])
获取 string1 string2 string3,一切都很好。
Here's what I want to do: Instead of typing string1 string2 string3
at the terminal, i want to type这是我想要做的:我想输入而不是在终端输入
string1 string2 string3
$ java ProgramName < input.txt
where "input.txt" contains string1, string2, and string3其中“input.txt”包含 string1、string2 和 string3
Edit: "input.txt" has one word on a separate line with an 'enter' at the end of the line编辑:“input.txt”在单独的一行中有一个单词,在该行的末尾有一个“输入”
string1
string2
stringn
This can be done it C++ ;这可以通过 C++ 完成; can it be done similarly in Java?
在Java中可以类似地完成吗?
You can do:你可以做:
export parameters=`cat file.txt`
java programname $parameters
note the inverse ` (not ')注意反' (不是')
or even:甚至:
java programname `cat file.txt`
Since you are redirecting a file to the standard input of your program, you can try the following:由于您将文件重定向到程序的标准输入,您可以尝试以下操作:
Scanner in = new Scanner(System.in);
String line = new String();
while(in.hasNext())//while there are lines on the file
{
line = in.nextLine();//read the line
//do stuff here
}
Please use this command:请使用此命令:
java MyProg "$(cat file.txt | tr '\n' ' ')"
If its not working please check that arguments are properly defined in source file.如果它不起作用,请检查源文件中是否正确定义了参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.