3

I was using the following function to convert a pdf to string:

        private String GetString(String filepath) throws IOException {
        InputStream inputStream = new FileInputStream(filepath);
        String inputStreamToString = inputStream.toString();
        byte[] byteArray = inputStreamToString.getBytes();
        String encoded = Base64.encodeToString(byteArray, Base64.DEFAULT);
        return encoded;
    }

I got the output as:

amF2YS5pby5GaWxlSW5wdXRTdHJlYW1ANTM1MDhmNTg=

I have found that this output is wrong. Because certainly when I encode a 2MB pdf file, it can't be so short. Actually I base64 decoded in php server and the output was an invalid pdf. So my question is what is missing in the function?

Ok. Problem solved. The following is the correct code to do this:

private String GetString(String filepath) throws IOException {
            InputStream inputStream = new FileInputStream(filepath);
            byte[] byteArray = IOUtils.toByteArray(inputStream);
            String encoded = Base64.encodeToString(byteArray, Base64.DEFAULT);
            return encoded;
        }
Ratul Doley
  • 499
  • 1
  • 6
  • 12

2 Answers2

0

Wrong part is: String inputStreamToString = inputStream.toString();. You'll not get the content of input stream as result, you'll get only something like "FileInputStream@021849".

You should read from stream in another way, e.g.: Android FileInputStream read() txt file to String

BTW, instead of reading file to String and converting it to byte array, you can read file straight to byte array.

Community
  • 1
  • 1
Sergey Glotov
  • 20,200
  • 11
  • 84
  • 98
-1

You can solve it with the second code. But "IOUtils" where the function code .