2

While i am running my code i'm getting error as "java.io.IOException:Attempted read from closed stream"

In my response i'm getting a PDF , i just want to read it and store it in my local.

My Code:

HttpResponse secondResponse = aHttpClient.execute(secondPost);

InputStream inputStream = secondResponse.getEntity().getContent();

FileOutputStream fileOutputStream = new FileOutputStream(new File("Result.pdf"));

int read = 0;

byte[] buffer = new byte[32768];

while ((read = inputStream.read(buffer)) > 0) {

fileOutputStream.write(buffer, 0, read);

}
Andrei Tigau
  • 2,010
  • 1
  • 6
  • 17
DopeBoy
  • 21
  • 2
  • May be this, https://stackoverflow.com/questions/41201790/how-to-get-pdf-file-from-web-using-java-streams – s_u_f Oct 30 '19 at 12:11
  • 1
    i don't see this post as any help in my matter, as i'm quite new to java can you please be more specific ,thanks @s_u_f – DopeBoy Oct 30 '19 at 12:16
  • It is (apparently) about "Apache HTTP Client" ... And so far I would trust the error message ("...stream is already closed, when you try to read it...") ...but *who/what* closes it!?? (is not obvious from your code snippet) ... so only the `HttpClient`/`HttpEntity`(implementations! ...the above are *interfaces*) can be blamed ... see [here a similar problem](https://stackoverflow.com/q/18636046/592355) , but there it is clarified what/who closes. – xerx593 Oct 30 '19 at 12:50
  • This will probably be helpful for you, to solve that exception : https://stackoverflow.com/questions/5034311/multiple-readers-for-inputstream-in-java/12107486#12107486 – Andrei Tigau Oct 30 '19 at 12:53
  • 2
    Are you sure you have shown all the relevant code? It seems the entity is being read twice. Could be read once even if you inspect/watch in your IDE.. Also, try this: https://stackoverflow.com/questions/18636046/java-io-ioexception-attempted-read-from-closed-stream – Teddy Oct 30 '19 at 12:56
  • I'm able to generate Result.pdf but it's empty, so i think error is coming in while() loop, and i'm closing all the connections after while() loop only. please help me with this ,thanks @xerx593 – DopeBoy Oct 30 '19 at 12:58
  • ...your IDE could also be blamed (for closing the stream, [see this reply](https://stackoverflow.com/a/41451826/592355)), but you say "runnning my code" *not "debugging"*. – xerx593 Oct 30 '19 at 13:02
  • 1
    Thanks @xerx593 for your help , i was consuming HttpEntity more than once, problem solved, again thanks a lot bro. – DopeBoy Oct 30 '19 at 13:14
  • glad 2 help, bro! :) And welcome to [so] & [tag:java] !;) (btw... you can post&accept your own answer!;) – xerx593 Oct 30 '19 at 13:17

0 Answers0