package com; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; public class Main { public static void main(String[] args) { // TODO 自动生成的方法存根 String name = "测试22 - Compressor Systems Holland (CSH) B.V..pdf"; String encodeString = urlEncodeString(name); System.out.println(encodeString); System.out.println(urlDecodeString(encodeString)); } /** * 编码 * @param str 需要编码的字符串 * @return 编码后的字符串 */ public static String urlEncodeString(String str) { String encode = ""; try { encode = URLEncoder.encode(str, String.valueOf(StandardCharsets.UTF_8)); } catch (UnsupportedEncodingException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } encode = encode.replace("+", "%20"); return encode; } /** * 解码 * @param str 需要解码的字符串 * @return 解码后的字符串 */ public static String urlDecodeString(String str) { String encode = ""; try { encode = URLDecoder.decode(str, String.valueOf(StandardCharsets.UTF_8)); } catch (UnsupportedEncodingException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } return encode; } }