简体   繁体   中英

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. 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. So it doesn't matter in which language the solution is. I tried in both. The encoding of my project is 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:

        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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM