首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Jakarta Commons Codec 使用指南:Base64、Hex、Metaphone/Soundex 編碼實戰

     編輯:Java 相關知識

功能概覽

  • Base64 / Hex:二進制↔文本編碼,傳輸存儲通用
  • Metaphone / Soundex:發音編碼,模糊匹配、去重、語音搜索核心

Maven 依賴

<dependency>
  <groupId>commons-codec</groupId>
  <artifactId>commons-codec</artifactId>
  <version>1.11</version>
</dependency>

Base64 編解碼

Base64 codec = new Base64();
String original = "中文";

byte[] encoded = codec.encode(original.getBytes("UTF-8"));
String encodedStr = new String(encoded); // 5bCP5piO

byte[] decoded = codec.decode(encoded);
String decodedStr = new String(decoded, "UTF-8"); // 中文

System.out.println("編碼前: " + original);
System.out.println("編碼後: " + encodedStr);
System.out.println("解碼後: " + decodedStr);

Hex 編解碼

Hex codec = new Hex();
String original = "中文";

char[] encoded = codec.encodeHex(original.getBytes("UTF-8"));
String encodedStr = new String(encoded); // e4b8ade69687

byte[] decoded = codec.decodeHex(encoded);
String decodedStr = new String(decoded, "UTF-8"); // 中文

System.out.println("編碼前: " + original);
System.out.println("編碼後: " + encodedStr);
System.out.println("解碼後: " + decodedStr);

發音編碼:Metaphone、RefinedSoundex、Soundex

Metaphone metaphone = new Metaphone();
RefinedSoundex refined = new RefinedSoundex();
Soundex soundex = new Soundex();

String[] words = {"resume", "resin"};
for (String w : words) {
    System.out.println("Original: " + w);
    System.out.println("Metaphone: " + metaphone.encode(w));       // RS / RSN
    System.out.println("RefinedSoundex: " + refined.encode(w)); // R250 / R250
    System.out.println("Soundex: " + soundex.encode(w));         // R250 / R250
    System.out.println();
}

算法特性對比

算法輸出長度精度典型應用
Soundex固定 4 碼 (字母+3數字)較低姓名檢索、簡單去重
RefinedSoundex可變長度中等改進版 Soundex
Metaphone可變長度最高 (英語)拼寫糾錯、語音搜索、MP3 標籤匹配

Metaphone 為同音詞生成相同鍵值,比 Soundex 準確,但無固定長度。選型視業務容錯率而定。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved