Java小程序:编码转换

时间:2021-12-29 13:30:50

importjava.io.UnsupportedEncodingException;

importjava.net.URLDecoder;

importjava.net.URLEncoder;

 

publicclass test {

      public static void main(String[] args){

              String str1 = "上海"; //仅可输中文

              String str3 ="%E5%95%86%E6%82%A6%E9%9D%92%E5%B9%B4%E4%BC%9A%E5%A4%A7%E9%85%92%E5%BA%97";//仅可输UTF-8字符

             

              //中文转UTF-8

               try {

                      System.out.println("(中文转 UTF-8:)");

                      System.out.println(URLEncoder.encode(str1, "UTF-8"));

             } catch (UnsupportedEncodingException e) {

                 // TODOAuto-generated catch block

                e.printStackTrace();

             }

            

             try {

                 String str2=(URLEncoder.encode(str1, "UTF-8"));

                System.out.println(URLDecoder.decode(str2, "UTF-8"));

             } catch (UnsupportedEncodingException e) {

                 // TODOAuto-generated catch block

                 e.printStackTrace();

             }

          //UTF-8字符转中文

 

             try {

                              System.out.println("(UTF-8 转 中文:)");

                       System.out.println(URLDecoder.decode(str3, "UTF-8"));

                    } catch (UnsupportedEncodingException e) {

                        // TODOAuto-generated catch block

                       e.printStackTrace();

                    }

             try {

                        String str4=(URLDecoder.decode(str3, "UTF-8"));

                              System.out.println(URLEncoder.encode(str4, "UTF-8"));

                           } catch (UnsupportedEncodingException e) {

                               // TODOAuto-generated catch block

                              e.printStackTrace();

                           }

          }

 }