URLEncoder的只編碼中文字元的類

來源:互聯網
上載者:User
原文地址:

  1. package log;
  2. import java.io.UnsupportedEncodingException;
  3. import java.net.URLEncoder;
  4. import java.util.regex.Matcher;
  5. import java.util.regex.Pattern;
  6. /**
  7.  * 正則替換字串裡面的漢字部分。
  8.  * 
  9.  * @author 趙學慶 www.java2000.net
  10.  */
  11. public class URLEncoderHZ {
  12.   public static void main(String[] args) throws Exception {
  13.     String str = "http://192.168.1.1:8080/resources/電話.xls";
  14.     System.out.println(encode(str, "UTF-8"));
  15.   }
  16.   private static String zhPattern = "[/u4e00-/u9fa5]+";
  17.   /**
  18.    * 替換字串卷
  19.    * 
  20.    * @param str 被替換的字串
  21.    * @param charset 字元集
  22.    * @return 替換好的
  23.    * @throws UnsupportedEncodingException 不支援的字元集
  24.    */
  25.   public static String encode(String str, String charset) throws UnsupportedEncodingException {
  26.     Pattern p = Pattern.compile(zhPattern);
  27.     Matcher m = p.matcher(str);
  28.     StringBuffer b = new StringBuffer();
  29.     while (m.find()) {
  30.       m.appendReplacement(b, URLEncoder.encode(m.group(0), charset));
  31.     }
  32.     m.appendTail(b);
  33.     return b.toString();
  34.   }
  35. }

運行結果
http://192.168.1.1:8080/resources/%E7%94%B5%E8%AF%9D.xls

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.