[英]Strange behaviour of readline in Java/Scala
I got a very strange problem. 我遇到了一个非常奇怪的问题。 I am trying to read the result of a command I am executing.
我正在尝试读取正在执行的命令的结果。 The code never reaches the println-Statement.
代码永远不会到达println-Statement。 It is just "hanging up" the program, if the end of the output is reached.
如果到达输出末尾,则只是“挂断”程序。 No failure and no exception.
没有失败也没有例外。
My project is a mix of Scala and Java. 我的项目是Scala和Java的混合体。 So it doesn't matter in which language the solution is.
因此,解决方案使用哪种语言都没有关系。 I tried in both.
我都尝试过。 The encoding of my project is Cp1252.
我的项目的编码是Cp1252。
Here is my code 这是我的代码
var fileScript = Runtime.getRuntime().exec(PathOfScript)
var isr:InputStreamReader = new InputStreamReader(fileScript.getInputStream())
var in = new BufferedReader(isr)
var line:String = ""
try {
while ({line = in.readLine(); line!= null}) {
println("line: "+line)
}
println("OUTSIDE !!!");
in.close();
}
That's strange... my Java version works just fine: 真奇怪……我的Java版本可以正常工作:
InputStreamReader isr = new InputStreamReader(new FileInputStream("c:\\anyfile"));
BufferedReader in = new BufferedReader(isr);
String line = "";
try {
while ((line = in.readLine()) != null) {
System.out.println("line: "+line);
}
System.out.println("OUTSIDE !!!");
in.close();
} catch (Exception ex) {
ex.printStackTrace();
}
I think that the problem is in fileScript: if it gives a stream and doesn't close it, you'll never get a null in the while loop. 我认为问题出在fileScript中:如果它提供了一个流而没有关闭它,则while循环中永远不会得到null。 Check that part.
检查该部分。 Try with a regular file (like I did in my example).
尝试使用常规文件(就像我在示例中所做的那样)。 If it works, the problem is surely in the fileScript object.
如果可行,则问题肯定出在fileScript对象中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.