Encoding as Base64 in Java

前端 未结 17 2506
失恋的感觉
失恋的感觉 2020-11-21 13:44

I need to encode some data in the Base64 encoding in Java. How do I do that? What is the name of the class that provides a Base64 encoder?


I tried to use the <

17条回答
  •  灰色年华
    2020-11-21 13:58

    In Java 8 it can be done as: Base64.getEncoder().encodeToString(string.getBytes(StandardCharsets.UTF_8))

    Here is a short, self-contained complete example:

    import java.nio.charset.StandardCharsets;
    import java.util.Base64;
    
    public class Temp {
        public static void main(String... args) throws Exception {
            final String s = "old crow medicine show";
            final byte[] authBytes = s.getBytes(StandardCharsets.UTF_8);
            final String encoded = Base64.getEncoder().encodeToString(authBytes);
            System.out.println(s + " => " + encoded);
        }
    }
    

    Output:

    old crow medicine show => b2xkIGNyb3cgbWVkaWNpbmUgc2hvdw==
    

提交回复
热议问题