0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【備忘録】JavaでBase64エンコード/デコード

Last updated at Posted at 2025-02-24

背景

今まで社内のExcelマクロでBase64のエンコードデコードを行ってきたが、これがJavaでもできることを知った。忘れないようにここに記す。

手法(Java8移行)

エンコード

1.java.util.Base64をインポートする。
2.Base64.getEncoder().encodeToStting();でString型にエンコード

デコード

1.java.util.Base64をインポートする。
2.Base64.getDecoder().decode()でエンコードされたString型をデコード

具体例

import java.util.Base64;

public class Main {
    public static void main(String[] args) {
        // 例として、元のバイト配列
        byte[] bin = "サンプルテキスト".getBytes(); // 文字列をバイト配列に変換

        // Base64でエンコードしてString型に変換
        String Bin = Base64.getEncoder().encodeToString(bin);
        System.out.println("Base64 Encoded: " + Bin);

        // Base64でエンコードされたStringをデコード
        byte[] decodedBytes = Base64.getDecoder().decode(Bin);

        // byte[]をString型に変換
        String decodedString = new String(decodedBytes);
        System.out.println("Decoded String: " + decodedString);
    }
}

出力結果

Base64 Encoded: 44OG44K544OI44Gn44GZ44CC44GT44Go44GE44Gf
Decoded String: サンプルテキスト
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?