[英]Java file input as command line argument
How do you process information in Java that was input from a file. 如何处理从文件输入的Java信息。 For Example: suppose you have a file input.txt.
例如:假设您有一个文件input.txt。 The contents of this file is: abcdefghizzzzjklmnop azzbcdefghijklmnop
该文件的内容是:abcdefghizzzzjklmnop azzbcdefghijklmnop
My hope would be that the information would be put into the argument array of strings such that the following code would output "abcdefghizzzzjklmnop" 我希望将信息放入字符串的参数数组中,以便下面的代码输出“abcdefghizzzzjklmnop”
class Test {
public static void main(String[] args) {
System.out.println(args[0]);
}
}
The command I have been using throws an array out of bound exception. 我一直在使用的命令抛出一个超出绑定异常的数组。 This command is:
这个命令是:
java Test < input.txt
java Test <input.txt
Non-file based arguments work fine though. 基于非文件的参数工作正常。 ie.
即。 java Test hello,a nd java Test < input.txt hello.
java测试你好,一个java测试<input.txt你好。
More information: I have tried putting the file contents all on one line to see if \\n \\r characters may be messing things up. 更多信息:我已经尝试将文件内容全部放在一行,看看\\ n \\ r \\ n字符是否可能搞乱了。 That didn't seem to help.
这似乎没有帮助。
Also, I can't use the bufferedreader class for this because this is for a program for school, and it has to work with my professors shell script. 此外,我不能使用bufferedreader类,因为这是针对学校的程序,它必须与我的教授shell脚本一起使用。 He went over this during class, but I didn't write it down (or I can't find it).
他在课堂上对此进行了讨论,但我没有把它写下来(或者我找不到它)。
Any help? 有帮助吗?
You should be able to read the input data from System.in
. 您应该能够从
System.in
读取输入数据。
Here's some quick-and-dirty example code. 这是一些快速而肮脏的示例代码。
javac Test.java; java Test < Test.java
javac Test.java; java Test < Test.java
: javac Test.java; java Test < Test.java
:
class Test
{
public static void main (String[] args)
{
byte[] bytes = new byte[1024];
try
{
while (System.in.available() > 0)
{
int read = System.in.read (bytes, 0, 1024);
System.out.write (bytes, 0, read);
}
} catch (Exception e)
{
e.printStackTrace ();
}
}
}
It seems any time you post a formal question about your problem, you figure it out. 无论何时你发布关于你的问题的正式问题,你都会想出来。
Inputing a file via "< input.txt" inputs it as user input rather than as a command line argument. 通过“<input.txt”输入文件将其作为用户输入而不是命令行参数输入。 I realized this shortly after I explained why the bufferedreader class wouldn't work.
在我解释为什么bufferedreader类无法工作之后不久就意识到了这一点。
Turns out you have to use the buffered reader class. 原来你必须使用缓冲的读者类。
I'm not sure why you want to pass the contents of a file as command line arguments unless you're doing some weird testbed. 我不确定你为什么要将文件的内容作为命令行参数传递,除非你做了一些奇怪的测试平台。
You could write a script that would read your file, generate a temporary script in which the java command is followed by your needs. 您可以编写一个可以读取文件的脚本,生成一个临时脚本,其中java命令将满足您的需求。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.