Java文件输入为命令行参数 [英] Java file input as command line argument
问题描述
如何处理从文件输入的Java中的信息。例如:假设您有一个文件input.txt。这个文件的内容是:
abcdefghizzzzjklmnop
azzbcdefghijklmnop
How do you process information in Java that was input from a file. For Example: suppose you have a file input.txt. The contents of this file is: abcdefghizzzzjklmnop azzbcdefghijklmnop
我的希望是将信息放入字符串的参数数组,以下代码将输出abcdefghizzzzjklmnop
My hope would be that the information would be put into the argument array of strings such that the following code would output "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:
input.txt
java Test < input.txt
不基于文件的参数可以正常工作。即。 java测试hello和java测试& input.txt hello。
Non-file based arguments work fine though. ie. java Test hello,a nd java Test < input.txt hello.
更多信息:
我试图把文件内容全部放在一行,看看\\\
\r字符是否可能弄乱了。这似乎没有帮助。
More information: I have tried putting the file contents all on one line to see if \n \r characters may be messing things up. That didn't seem to help.
此外,我不能使用bufferedreader类,因为这是一个学校的程序,它必须与我的教授的shell脚本一起工作。
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. He went over this during class, but I didn't write it down (or I can't find it).
任何帮助?
推荐答案
您应该能够从 System.in
中读取输入数据。
You should be able to read the input data from System.in
.
这里有一些简单肮脏的示例代码。 javac Test.java; java Test& Test.java
:
Here's some quick-and-dirty example code. 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 ();
}
}
}
这篇关于Java文件输入为命令行参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!