Java encoding base64 with encoding

Кодирование и декодирование Base64 в Java

В этом посте будет обсуждаться кодирование и декодирование Base64 с использованием простой Java, Guava и Apache Commons.

Base64 представляет собой группу подобных схем кодирования двоичного кода в текст, представляющих двоичные данные в формате строки ASCII путем преобразования их в radix-64 представление. Каждый Base64 цифра представляет ровно 6 бит данных, что означает, что 3 байта могут быть представлены 4 6-битными Base64 цифры.

Схемы кодирования Base64 обычно используются, когда необходимо кодировать двоичные данные, которые необходимо хранить и передавать через носители, предназначенные для работы с текстовыми данными. Это необходимо для того, чтобы данные оставались неповрежденными без изменений во время транспортировки. Base64 обычно используется в ряде приложений, включая электронную почту через MIME и хранение сложных данных в XML .

1. Использование Java 8

Java 8, наконец, обеспечила поддержку возможностей кодирования и декодирования Base64, предоставив Base64, Base64.Encoder а также Base64.Decoder класс полезности. Base64 класс состоит из статических методов для получения экземпляров энкодеров ( Base64.Encoder ) и декодеры ( Base64.Decoder ) для схемы кодирования Base64.

В следующей программе используется Base64.Encoder.encodeToString() метод для кодирования указанного массива байтов в кодированную строку Base64 и Base64.Decoder.decode() метод обратного декодирования строки в кодировке Base64 во вновь выделенный массив байтов.

Читайте также:  Пример простейшей нейронной сети python

Источник

Class Base64

Unless otherwise noted, passing a null argument to a method of this class will cause a NullPointerException to be thrown.

Nested Class Summary

This class implements a decoder for decoding byte data using the Base64 encoding scheme as specified in RFC 4648 and RFC 2045.

This class implements an encoder for encoding byte data using the Base64 encoding scheme as specified in RFC 4648 and RFC 2045.

Method Summary

Returns a Base64.Encoder that encodes using the MIME type base64 encoding scheme with specified line length and line separators.

Methods declared in class java.lang.Object

Method Details

getEncoder

getUrlEncoder

getMimeEncoder

getMimeEncoder

Returns a Base64.Encoder that encodes using the MIME type base64 encoding scheme with specified line length and line separators.

getDecoder

getUrlDecoder

getMimeDecoder

Report a bug or suggest an enhancement
For further API reference and developer documentation see the Java SE Documentation, which contains more detailed, developer-targeted descriptions with conceptual overviews, definitions of terms, workarounds, and working code examples. Other versions.
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2023, Oracle and/or its affiliates, 500 Oracle Parkway, Redwood Shores, CA 94065 USA.
All rights reserved. Use is subject to license terms and the documentation redistribution policy.

Источник

Java encoding base64 with encoding

This class implements an encoder for encoding byte data using the Base64 encoding scheme as specified in RFC 4648 and RFC 2045. Instances of Base64.Encoder class are safe for use by multiple concurrent threads. Unless otherwise noted, passing a null argument to a method of this class will cause a NullPointerException to be thrown.

Method Summary

Encodes all bytes from the specified byte array into a newly-allocated byte array using the Base64 encoding scheme.

Encodes all bytes from the specified byte array using the Base64 encoding scheme, writing the resulting bytes to the given output byte array, starting at offset 0.

Encodes all remaining bytes from the specified byte buffer into a newly-allocated ByteBuffer using the Base64 encoding scheme.

Returns an encoder instance that encodes equivalently to this one, but without adding any padding character at the end of the encoded byte data.

Methods inherited from class java.lang.Object

Method Detail

encode

public byte[] encode(byte[] src)

Encodes all bytes from the specified byte array into a newly-allocated byte array using the Base64 encoding scheme. The returned byte array is of the length of the resulting bytes.

encode

public int encode(byte[] src, byte[] dst)

Encodes all bytes from the specified byte array using the Base64 encoding scheme, writing the resulting bytes to the given output byte array, starting at offset 0. It is the responsibility of the invoker of this method to make sure the output byte array dst has enough space for encoding all bytes from the input byte array. No bytes will be written to the output byte array if the output byte array is not big enough.

encodeToString

Encodes the specified byte array into a String using the Base64 encoding scheme. This method first encodes all input bytes into a base64 encoded byte array and then constructs a new String by using the encoded byte array and the ISO-8859-1 charset. In other words, an invocation of this method has exactly the same effect as invoking new String(encode(src), StandardCharsets.ISO_8859_1) .

encode

Encodes all remaining bytes from the specified byte buffer into a newly-allocated ByteBuffer using the Base64 encoding scheme. Upon return, the source buffer’s position will be updated to its limit; its limit will not have been changed. The returned output buffer’s position will be zero and its limit will be the number of resulting encoded bytes.

wrap

Wraps an output stream for encoding byte data using the Base64 encoding scheme. It is recommended to promptly close the returned output stream after use, during which it will flush all possible leftover bytes to the underlying output stream. Closing the returned output stream will close the underlying output stream.

withoutPadding

Returns an encoder instance that encodes equivalently to this one, but without adding any padding character at the end of the encoded byte data. The encoding scheme of this encoder instance is unaffected by this invocation. The returned encoder instance should be used for non-padding encoding operation.

Submit a bug or feature
For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
Copyright © 1993, 2023, Oracle and/or its affiliates. All rights reserved. Use is subject to license terms. Also see the documentation redistribution policy.

Источник

Class Base64.Encoder

This class implements an encoder for encoding byte data using the Base64 encoding scheme as specified in RFC 4648 and RFC 2045.

Instances of Base64.Encoder class are safe for use by multiple concurrent threads.

Unless otherwise noted, passing a null argument to a method of this class will cause a NullPointerException to be thrown.

If the encoded byte output of the needed size can not be allocated, the encode methods of this class will cause an OutOfMemoryError to be thrown.

Method Summary

Encodes all bytes from the specified byte array into a newly-allocated byte array using the Base64 encoding scheme.

Encodes all bytes from the specified byte array using the Base64 encoding scheme, writing the resulting bytes to the given output byte array, starting at offset 0.

Encodes all remaining bytes from the specified byte buffer into a newly-allocated ByteBuffer using the Base64 encoding scheme.

Returns an encoder instance that encodes equivalently to this one, but without adding any padding character at the end of the encoded byte data.

Methods declared in class java.lang.Object

Method Details

encode

Encodes all bytes from the specified byte array into a newly-allocated byte array using the Base64 encoding scheme. The returned byte array is of the length of the resulting bytes.

encode

Encodes all bytes from the specified byte array using the Base64 encoding scheme, writing the resulting bytes to the given output byte array, starting at offset 0. It is the responsibility of the invoker of this method to make sure the output byte array dst has enough space for encoding all bytes from the input byte array. No bytes will be written to the output byte array if the output byte array is not big enough.

encodeToString

Encodes the specified byte array into a String using the Base64 encoding scheme. This method first encodes all input bytes into a base64 encoded byte array and then constructs a new String by using the encoded byte array and the ISO-8859-1 charset. In other words, an invocation of this method has exactly the same effect as invoking new String(encode(src), StandardCharsets.ISO_8859_1) .

encode

Encodes all remaining bytes from the specified byte buffer into a newly-allocated ByteBuffer using the Base64 encoding scheme. Upon return, the source buffer’s position will be updated to its limit; its limit will not have been changed. The returned output buffer’s position will be zero and its limit will be the number of resulting encoded bytes.

wrap

Wraps an output stream for encoding byte data using the Base64 encoding scheme. It is recommended to promptly close the returned output stream after use, during which it will flush all possible leftover bytes to the underlying output stream. Closing the returned output stream will close the underlying output stream.

withoutPadding

Returns an encoder instance that encodes equivalently to this one, but without adding any padding character at the end of the encoded byte data. The encoding scheme of this encoder instance is unaffected by this invocation. The returned encoder instance should be used for non-padding encoding operation.

Report a bug or suggest an enhancement
For further API reference and developer documentation see the Java SE Documentation, which contains more detailed, developer-targeted descriptions with conceptual overviews, definitions of terms, workarounds, and working code examples. Other versions.
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2023, Oracle and/or its affiliates, 500 Oracle Parkway, Redwood Shores, CA 94065 USA.
All rights reserved. Use is subject to license terms and the documentation redistribution policy.

Источник

Java encoding base64 with encoding

Unless otherwise noted, passing a null argument to a method of this class will cause a NullPointerException to be thrown.

Nested Class Summary

This class implements a decoder for decoding byte data using the Base64 encoding scheme as specified in RFC 4648 and RFC 2045.

This class implements an encoder for encoding byte data using the Base64 encoding scheme as specified in RFC 4648 and RFC 2045.

Method Summary

Returns a Base64.Encoder that encodes using the MIME type base64 encoding scheme with specified line length and line separators.

Methods declared in class java.lang.Object

Method Detail

getEncoder

getUrlEncoder

getMimeEncoder

getMimeEncoder

public static Base64.Encoder getMimeEncoder​(int lineLength, byte[] lineSeparator)

Returns a Base64.Encoder that encodes using the MIME type base64 encoding scheme with specified line length and line separators.

getDecoder

getUrlDecoder

getMimeDecoder

Report a bug or suggest an enhancement
For further API reference and developer documentation see the Java SE Documentation, which contains more detailed, developer-targeted descriptions with conceptual overviews, definitions of terms, workarounds, and working code examples.
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2023, Oracle and/or its affiliates, 500 Oracle Parkway, Redwood Shores, CA 94065 USA.
All rights reserved. Use is subject to license terms and the documentation redistribution policy.

Источник

Оцените статью