1

I am getting a JSON response from webservice call as

![JSON REsponse from web service call]1

I have to save this file to my system. I am using the following code:

        BASE64Decoder decoder = new BASE64Decoder();
        byte[] decodedBytes = decoder.decodeBuffer(response);
        ByteArrayInputStream bis = new ByteArrayInputStream(decodedBytes);         
        bis.close();
        File file = new File("C:/image one.jpeg");
        FileOutputStream fop = new FileOutputStream(file);
        fop.write(decodedBytes);
        fop.flush();
        fop.close();

The file gets saved but is corrupt and can't be opened. Can anybody shed some light on what I am doing wrong?

Ram
  • 79
  • 3
  • 16

1 Answers1

1

Try to use Base64 class from java.util.Base64

byte[] decodedBytes = Base64.getDecoder().decode(base64String);

Or Base64 from org.apache.commons.codec.binary

byte[] decodedBytes = Base64.decodeBase64(base64String);

And you won't need ByteArrayInputStream object

See this link for more detailed answer

Ruslan
  • 6,090
  • 1
  • 21
  • 36
  • Thanks! That worked.. Can you enlighten me as to why did ByteArrayInputStream not work? – Ram Nov 28 '18 at 14:20
  • @Ram you have created `ByteArrayInputStream` object but didn't use it anywhere else. The constructor of `ByteArrayInputStream` doesn't change the original array you passed. So I guess the problem was in `BASE64Decoder` class – Ruslan Nov 28 '18 at 22:00