Decoding a Base64 string in Java

前端 未结 4 1701
心在旅途
心在旅途 2020-12-05 09:15

I\'m trying to decode a simple Base64 string, but am unable to do so. I\'m currently using the org.apache.commons.codec.binary.Base64 package.

The test

相关标签:
4条回答
  • 2020-12-05 09:43

    If you don't want to use apache, you can use Java8:

    byte[] decodedBytes = Base64.getDecoder().decode("YWJjZGVmZw=="); 
    System.out.println(new String(decodedBytes) + "\n");
    
    0 讨论(0)
  • 2020-12-05 09:50

    Modify the package you're using:

    import org.apache.commons.codec.binary.Base64;
    

    And then use it like this:

    byte[] decoded = Base64.decodeBase64("YWJjZGVmZw==");
    System.out.println(new String(decoded, "UTF-8") + "\n");
    
    0 讨论(0)
  • 2020-12-05 09:56

    The following should work with the latest version of Apache common codec

    byte[] decodedBytes = Base64.getDecoder().decode("YWJjZGVmZw==");
    System.out.println(new String(decodedBytes));
    

    and for encoding

    byte[] encodedBytes = Base64.getEncoder().encode(decodedBytes);
    System.out.println(new String(encodedBytes));
    
    0 讨论(0)
  • 2020-12-05 09:57

    Commonly base64 it is used for images. if you like to decode an image (jpg in this example with org.apache.commons.codec.binary.Base64 package):

    byte[] decoded = Base64.decodeBase64(imageJpgInBase64);
    FileOutputStream fos = null;
    fos = new FileOutputStream("C:\\output\\image.jpg");
    fos.write(decoded);
    fos.close();
    
    0 讨论(0)
提交回复
热议问题