Store base64 encoded string as file
Asked Answered
T

1

5

I have a web service that returns a base64 encoded string of a PDF file.

I want to save this file to the SD Card. but when i try do this, adobe reader tells me that the file is corrupt. obviously i am not saving it properly.

byte[] pdfAsBytes = Base64.decode(resultsRequestSOAP.toString(), 0);

File filePath = new File(Environment.getExternalStorageDirectory()+"/braodcasts.pdf");
FileOutputStream os = new FileOutputStream(filePath, true);
os.write(pdfAsBytes);
os.close();

resultsRequestSOAP.toString() looks like this:

JVBERi0xLjUNCiW1tbW1DQoxIDAgb2JqDQo8PC9UeXBlL0NhdGFsb2cvUGFnZXMgMiAwIFIvTGFuZyhlbi1JRSkgPj4NCmVuZG9iag0KMiAwIG9iag0KPDwvVHlwZS9QYWdlcy9Db3VudCAxL0tpZHNbIDMgMCBSXSA+Pg0KZW5kb2JqDQozIDAgb2JqDQo8PC9UeXBlL1BhZ2UvUGFyZW50IDIgMCBSL1Jlc291cmNlczw8L0ZvbnQ8PC9GMSA1IDAgUj4+L0V4dEdTdGF0ZTw8L0dTNyA3IDAgUi9HUzggOCAwIFI+Pi9YT2JqZWN0PDwvSW1hZ2U5IDkgMCBSPj4vUHJvY1NldFsvUERGL1RleHQvSW1hZ2VCL0ltYWdlQy9JbWFnZUldID4+L01lZGlhQm94WyAwIDAgNTk1LjMyIDQxOS41Ml0gL0NvbnRlbnRzIDQgMCBSL0dyb3VwPDwvVHlwZS9Hcm91cC9TL1RyYW5zcGFyZW5jeS9DUy9EZXZpY2VSR0I+Pi9UYWJzL1M+Pg0KZW5kb2JqDQo0IDAgb2JqDQo8PC9GaWx0ZXIvRmxhdGVEZWNvZGUvTGVuZ3RoIDE0ND4+DQpzdHJlYW0NCnicLY29CgIxEIT7hX2HKVVw3ewluUsr/qCdGLAQC5HzqlPU9wdjcKaaYZhvmZkWGwfnRD3ynclBix18l6T0TRJ1yGOZbY8thg+TYqip+6ct03mC6QV5z7Quhy+muYpWWWjhLEqKCClIYzBTCRHvnuk0w4PJuyi+Uk07MbRWsWV6+2F343XoE1ZPHJi+nDkiaw0KZW5kc3RyZWFtDQplbmRvYmoNCjUgMCBvYmoNCjw8L1R5cGUvRm9udC9TdWJ0eXBlL1RydWVUeXBlL05hbWUvRjEvQmFzZUZvbnQvQUJDREVFK0NhbGlicmkvRW5jb2RpbmcvV2luQW5zaUVuY29kaW5nL0ZvbnREZXNjcmlwdG9yIDYgMCBSL0ZpcnN0Q2hhciAzMi9MYXN0Q2hhc

Thats just a snippet!

Thanks

Teflon answered 7/6, 2011 at 16:37 Comment(5)
It looks like you're opening it for appending. Is there already a file with that name to which you're appending?Diplex
i'm not opening it for append, i'm overwriting the file each timeTeflon
Have a look at the PDF in a text editor. The first line should be something like "%PDF-1.4" and the last line should be "%%EOF".Diplex
yeah it is, i just wasn't flushing the file after writing. Thanks for your help :)Teflon
I just noticed all pdf's start with JVBERi0xLj. And I was only using the first part to check if my pdf changed or not...Avivah
B
12

Perhaps you can flush the FileOutputStream before you close it.

os.write(pdfAsBytes);
os.flush();
os.close();
Beslobber answered 7/6, 2011 at 16:53 Comment(3)
That surprises me. I would've expected that close would automatically flush any unwritten bytes.Diplex
the flush() method in FileOutputStream does nothing, it is inherited from OutputStream. As the doc says Flushes this stream. Implementations of this method should ensure that any buffered data is written out. This implementation does nothing.Avivah
I think it flushes out any remaining bytes that might be in the stream, which explains why it fixed my issue.Teflon

© 2022 - 2024 — McMap. All rights reserved.