Base 64 : Illegal base64 character 3 Exception

59 Views Asked by At

I have a text file with a base64 encoded value, and I tried to decode that text file and save it into a PDF format. Below is my code

File inputfile = new File('/Users/Downloads/DownloadedPDF.txt')
File outputfile = new File('/Users/Downloads/test64.pdf')
byte[] data
try {
    FileInputStream fileInputStream = new FileInputStream(inputfile)
    data = new byte[(int) inputfile.length()]
    fileInputStream.read(data)
    fileInputStream.close()
}catch(Exception e) {
    e.getStackTrace()
}
//Decode the data
byte[] decoded = java.util.Base64.getDecoder().decode(data)
try {
    FileOutputStream fileOutputStream = new FileOutputStream(outputfile)
    //Write the decoded details to the output file [pdf format]
    fileOutputStream.write(decoded)
    fileOutputStream.flush()
    fileOutputStream.close()
}catch(Exception e) {
    e.getStackTrace()
}

While executing the code I received the below error.

java.lang.IllegalArgumentException: Illegal base64 character 3
    at java_util_Base64$Decoder$decode$0.call(Unknown Source)

i tried the below one using the URL decoder, but still received the same error.

byte[] decoded = Base64.getUrlDecoder().decode(data)
1

There are 1 best solutions below

2
jtahlborn On

Reading bytes from a stream does not guarantee that it will read all the bytes you request. try readNBytes() instead. (or you can use readAllBytes() as mentioned by @DavidConrad).