0

When i hit an API through postman i am able to download a pdf file. When i hit the same API through java code i get pdf content in ResponseBody. And i am able to create a new pdf file with the responsebody content but when i open the file it is blank.

my question is how can i create a new file with the same content as in response.

i tried the foll. code to convert the response

file  = new File("/home/abc.pdf");
            outputStream = new BufferedOutputStream(new FileOutputStream(file));
            if (!file.exists()) {
                file.createNewFile();
            }

            byte[] contentInBytes = response.getBody().getBytes();
            System.out.println(Arrays.toString(contentInBytes));

            outputStream.write(contentInBytes);
            outputStream.flush();
            outputStream.close();
I2rz
  • 3
  • 1
  • 5
  • Possible duplicate of [How to get PDF file from web using java streams](https://stackoverflow.com/questions/41201790/how-to-get-pdf-file-from-web-using-java-streams) – Hulk Aug 01 '18 at 14:33

1 Answers1

0

Creating a temporary byte[] array to store the entire response body before saving it to a file is wasteful. You want to write the response InputStream to the OutputStream of your file.

This can be done in few ways, one will be to use Guava's ByteStreams.copy() e.g.:

try (OutputStream out = Files.newOutputStream(Paths.get("abc.pdf")) {
    ByteStreams.copy(response.getBody(), out);
}
Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111