javascalabufferedreaderreadlineinputstreamreader

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();
}

Solution

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