tags:

views:

56

answers:

4

this function when called in a loop is sometimes giving null as outstream while other times not .. any reason why ? i am writing the outstream into text file sometimes i get empty text file . why ? if i run the loop 20 times .. i sometimes get empty text file on 3 random occasions sometimes 4 or 2 random occasions. what should i do ?

public void decrypt(InputStream in, OutputStream out) {
  try {
    // Bytes read from in will be decrypted
    in = new CipherInputStream(in, dcipher);

    // Read in the decrypted bytes and write the cleartext to out
    int numRead = 0;
    while ((numRead = in.read(buf)) >= 0) {
      out.write(buf, 0, numRead);
    }
    out.close();
  }
  catch (java.io.IOException e) {
  }
}
+4  A: 

I think this happens because you are closing the output stream in your function. This way, the next iteration of your cycle will try to write to an already closed output stream. It will throw an IOException but you are ignoring it. Try closing the output stream after your loop and not in the method.

InputStream in = null;
OutputStream out = null;
try {
   in = Initialize input stream
   out = Initialize output stream
   for (int i = 0; i < 10; i++) {
      decrypt(in, out);
   }
}finally {
   try {
      if (out != null)
         out.close();
   }finally {
      if (in != null)
         in.close();
   }
}
bruno conde
i did this and commented out.close from the function.. but nothing changed....if possible can you do a remote login to my computer .. cause i dont konw how to share the whole eclipse project.
rover12
Can't you post the code that is calling decrypt and is creating the input/output streams?
bruno conde
A: 

"Never close something that you haven't opened" - don't know if that's a golden rule, but it nearly always leads to trouble when you close a resource in a subroutine - either the ressource is closed next time you need it or the resource is not closed because you changed the code...

Andreas_D
+2  A: 

you should definitely fix this part of your code:

catch (java.io.IOException e) { }

and do at least some logging there. That way you'll find out why you have the problem you described.

anthony
+3  A: 

If an exception is thrown by any code in your try block , it is ignored (since you have nothing in your catch clause.

You might want to :

  • actually do something in the catch clause (at least print the message of the exception - try e.printStackTrace())
  • instead of doing the out.close() call in the try block, do it in a finally clause after the catch block (so that it happens even if there is an error)
  • also , as pointed out by bruno, if you're always reusing the same output stream for evey calls of decrypt, you should not close it inside the function. However you might want to flush() it inside you loop.
phtrivier