情深忆往缠绵 2022-06-21 19:38 采纳率: 44%
浏览 32
已结题

new String(s.getBytes("ISO-8859-1"), "UTF-8")问题

问题遇到的现象和发生背景

new String(s.getBytes("ISO-8859-1"), "UTF-8")转换后还是乱码怎么回事

问题相关代码,请勿粘贴截图
package javaweb1;

public class ChineseToString {
    public ChineseToString() {
        // TODO Auto-generated constructor stub
    }

    /**
     * 构造方法
     */
    public String toString(String s) {
        String text = "";
        // 判断要转码的字符串是否有效
        if (!s.equals("") && !s.equals("null")) {
            try {
                // 将字符串进行编码处理
                text = new String(s.getBytes("ISO-8859-1"), "UTF-8");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return text;
    }
    /**
     * 转码处理字符串
     * 
     * @param s 要转码的字符串
     *          
     * @return 转码后的字符串
     */
    public static void main(String[] args) {
        System.out.println(new ChineseToString().toString("达到"));
    }
}


运行结果及报错内容

img

我想要达到的结果

正常显示中文

  • 写回答

1条回答 默认 最新

  • 赵4老师 2022-06-22 10:59
    关注

    String.getBytes()JAVA编码转换的详细过程 https://wenku.baidu.com/view/fc314c32f28583d049649b6648d7c1c708a10b7b.html

    package Test;
    
    public class ChineseToString {
        public ChineseToString() {
            // TODO Auto-generated constructor stub
        }
    
        /**
         * 构造方法
         */
        public String toString(String s) {
            String text = "";
            // 判断要转码的字符串是否有效
            if (!s.equals("") && !s.equals("null")) {
                try {
                    // 将字符串进行编码处理
                    text = new String(s.getBytes("ISO-8859-1"), "UTF-8");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return text;
        }
        /**
         * 转码处理字符串
         *
         * @param s 要转码的字符串
         *
         * @return 转码后的字符串
         */
        public static void main(String[] args) {
    //      System.out.println(new ChineseToString().toString("达到"));
            try {
                String s=new String("达到".getBytes("UTF-8"),"ISO-8859-1");
                System.out.println(new ChineseToString().toString(s));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    
    
    
    评论 编辑记录

报告相同问题?

问题事件

  • 已结题 (查看结题原因) 6月22日
  • 创建了问题 6月21日