JAVA 中文 unicode 相互转换 文件读取

package com.test;
import org.junit.Test;

public class JunitTest {
  
    @Test
    public void test(){
        String path = "D:\1.txt";
        String newPath = "D:\2.txt";
        try { // 防止文件建立或读取失败,用catch捕捉错误并打印,也可以throw

            /* 读入TXT文件 */// 要读取以上路径的input。txt文件
            File filename = new File(path);
            // 建立一个输入流对象reader
            InputStreamReader reader = new InputStreamReader(new FileInputStream(filename));
            // 建立一个对象,它把文件内容转成计算机能读懂的语言
            BufferedReader br = new BufferedReader(reader);
            String line = "";
            line = br.readLine();
                /* 写入Txt文件 */// 相对路径,如果没有则要建立一个新的output。txt文件
            File writename = new File(newPath);
            // 创建新文件
            writename.createNewFile();
            BufferedWriter out = new BufferedWriter(new FileWriter(writename));
            while (line != null) {
                // 一次读入一行数据
                line = br.readLine();
                System.out.println(line.toString());
                // 
即为换行
                out.write(cnToUnicode(line)+"
");
                out.flush(); // 把缓存区内容压入文件
            }
            out.close(); // 最后记得关闭文件

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Test
    public void test1(){
        System.out.println(cnToUnicode("部队"));
        System.out.println(unicodeToCn("\u4e2d\u56fd\u4eba\u6c11\u89e3\u653e\u519b\u37\u31\u39\u38\u38\u90e8\u961f"));
    }

    /**
     * 中文转unicode
     * @param cn
     * @return
     */
    private static String cnToUnicode(String cn) {
        char[] chars = cn.toCharArray();
        String returnStr = "";
        for (int i = 0; i < chars.length; i++) {
            returnStr += "\u" + Integer.toString(chars[i], 16);
        }
        return returnStr;
    }

    /**
     * unicode转中文
     * @param unicode
     * @return
     */
    private static String unicodeToCn(String unicode) {
        /** 以  u 分割,因为java注释也能识别unicode,因此中间加了一个空格*/
        String[] strs = unicode.split("\\u");
        String returnStr = "";
        // 由于unicode字符串以  u 开头,因此分割出的第一个字符是""。
        for (int i = 1; i < strs.length; i++) {
            returnStr += (char) Integer.valueOf(strs[i], 16).intValue();
        }
        return returnStr;
    }

}

  

原文地址:https://www.cnblogs.com/qinxu/p/8295843.html