如何使用bash将文件重定向为Java程序的输入? [英] How to redirect a file as an input to Java program with bash?
问题描述
我的代码大致如下所示:
My code roughly looks like this:
InputStreamReader isReader = new InputStreamReader(System.in);
BufferedReader bufReader = new BufferedReader(isReader);
while (true) {
try {
String inputStr = null;
if ((inputStr=bufReader.readLine()) != null) {
//DO SOMETHING
}
else {
System.out.println("input is null");
}
}
catch (Exception e) {
//DO SOMETHING
}
}
当我跑步时
java -classpath ../src test.TestProgram < filename
它处理文件中的第一行,但它会一直打印输入为空
并且永远不会进入第二行。
it process the first line in the file well, but it keeps printing input is null
and never goes to the second line.
如何修改我的程序以告诉它让错误输入去掉到下一行?
How can I modify my program to to tell it let the error input go and go to the next line?
PS:我需要进行的文件如下所示:
PS: the file I need to precess is like below:
111111111
111111112
111111113
...
我试过
java -classpath ../src test.TestProgram < filename
echo `cat filename` | java -classpath ../src test.TestProgram
java -classpath ../src test.TestProgram <<< `cat filename`
他们都失败了
我的错...我在循环中放了BufferedReader bufReader = new BufferedReader(new InputStreamReader(System.in))谢谢大家!
推荐答案
您的代码实际上很好,它适用于Mac OSX Java 1.6.0。我做了一些小改动:
Your code is actually fine and it works for me on Mac OSX Java 1.6.0. I made a few minor changes:
public static void main(String[] args) {
InputStreamReader isReader = new InputStreamReader(System.in);
BufferedReader bufReader = new BufferedReader(isReader);
while (true) {
try {
String inputStr = null;
if ((inputStr = bufReader.readLine()) != null) {
System.out.println(inputStr);
} else {
System.out.println("input is null");
return; //end on first null
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
我跑:
java Test.java < data.txt
并输出:
111111111
111111112
111111113
input is null
你是如何制作输入文件的?也许你的行结尾是非标准的?
How did you make your input file? Perhaps your line endings are non-standard?
这是你的代码清理了一下:
Here is your code cleaned up a bit:
public static void main(String[] args) {
BufferedReader bufReader = new BufferedReader(new InputStreamReader(System.in));
String inputStr = null;
try {
while ((inputStr = bufReader.readLine()) != null) {
System.out.println(inputStr);
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("end of file");
}
这篇关于如何使用bash将文件重定向为Java程序的输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!