-1

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)
9
  • 1
    What is the data you are trying to decode? Commented Mar 19, 2024 at 14:04
  • Is this Groovy or Kotlin? That doesn't look like valid Java code (no semicolons). Commented Mar 19, 2024 at 14:05
  • 1
    have you tried running the encoded data through some other base64 decoder to verify that it is actually valid? Commented Mar 19, 2024 at 14:05
  • @DavidConrad This is Groovy script; Commented Mar 19, 2024 at 14:06
  • 1
    If it's Groovy then it should be tagged groovy rather than java. Commented Mar 19, 2024 at 14:08

1 Answer 1

2

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).

Sign up to request clarification or add additional context in comments.

2 Comments

Or readAllBytes().
Or wrap the input stream so it decodes on the fly, instead of loading the entire base64 in memory before decoding. The OP can then use transferTo to write to the destination file, removing the need for materializing the entire file in memory as well. (Although I'd question a system where a PDF was saved in a base64 encoded text file to begin with.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.