示例:我有一个班级
public class MyClass0 {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Input 1st string");
String s1 = reader.readLine();
System.out.println("Input 2nd string");
String s2 = reader.readLine();
System.out.println("Input 3rd string");
String s3 = reader.readLine();
System.out.println("1st string is " + s1);
System.out.println("2nd string is " + s2);
System.out.println("3rd string is " + s3);
}
}
我从脚本中调用它并通过此处文档传递输入
#!/bin/sh
export JAVA_HOME=$HOME/java/jdk1.7.0_21;
export PATH=$JAVA_HOME/bin:$PATH;
java MyClass0;
./myscript.sh <<'EOL'
123
456
789
EOL
它按预期工作:
1st string is 123
2nd string is 456
3rd string is 789
但如果这样做:
public class MyClass0 {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Input 1st string");
String s1 = reader.readLine();
System.out.println("1st string is " + s1);
MyClass1.read();
}
}
public class MyClass1 {
public static void read() throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String s2 = reader.readLine();
String s3 = reader.readLine();
System.out.println("2nd string is " + s2);
System.out.println("3rd string is " + s3);
}
}
我得到了这个:
1st string is 123
2nd string is null
3rd string is null
任何想法如何使其发挥作用?我能做些什么才能采取其他两个论点?我无法改变课程。
答案 0 :(得分:1)
这是因为你已经打开了2个缓冲读卡器来处理相同的输入流。
在MyClass0.main中,您创建一个并读取第一行。在内部,BufferedRead已尽可能多地读取(这里是完整的文档),返回第一行,并准备返回以下行而不进行任何IO访问。
你在MyClass1.read中打开第二个BufferedReader。不幸的是,System.in
已经定位在文件末尾,任何阅读都将返回null
。
如何修复: 恕我直言,更简洁的方法是将BufferedReader传递给MyClass1.read:
...
MyClass1.read(reader);
}
}
public class MyClass1 {
public static void read(Reader reader) throws IOException {
String s2 = reader.readLine();
String s3 = reader.readLine();
System.out.println("2nd string is " + s2);
System.out.println("3rd string is " + s3);
}
}
答案 1 :(得分:0)
问题在于您正在使用BufferedReader
缓冲数据以供应用程序读取,如果您希望通过第二代代码获得所需结果,则需要在不缓冲的情况下阅读System.in
。这是一种方法,可以帮助您从System.in
读取而无需缓冲任何内容
public static String readLine(InputStream inputStream) throws IOException {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int c;
for (c = inputStream.read(); c != '\n' && c != -1 ; c = inputStream.read()) {
byteArrayOutputStream.write(c);
}
if (c == -1 && byteArrayOutputStream.size() == 0) {
return null;
}
String line = byteArrayOutputStream.toString("UTF-8");
return line;
}