JDK自带工具native2ascii

背景在做Java开发的时候,常常会出现一些乱码,或者无法正确识别或读取的文件,比如常见的validator验证用的消息资源(properties)文件就需要进行Unicode重新编码。原因是java默认的编码方式为unicode,而我们的计算机系统编码常常是GBK等编码,需要将系统的编码转换为java正确识别的编码。

native2ascii - Creates localizable applications by converting a file with characters in any supported character encoding to one with ASCII and/or Unicode escapes or vice versa.

native2ascii命令说明:
native2ascii [options] [inputfile] [outputfile]

[options]:

  -reverse:Perform the reverse operation: Converts a file encoded in ISO-8859-1 with Unicode escapes to a file in any character encoding supported by the jre.

  -encoding encoding name:Specifies the name of the character encoding to be used by the conversion procedure.

[inputfile] [outputfile]

  inputfile:The encoded file to be converted to ASCII.
  outputfile:The converted ASCII file.

假设系统的默认编码为UTF-8,有utf-8编码保存的文件zh.txt内容“熔岩”。

A:将zh.txt转换为Unicode编码,输出文件到u.txt
native2ascii zh.txt u.txt
打开u.txt,内容为“u7194u5ca9”。

B:将zh.txt转换为Unicode编码,输出到控制台
native2ascii zh.txt
u7194u5ca9
可以看到,控制台输出了“u7194u5ca9”。

C:将zh.txt转换为ISO8859-1编码,输出文件到i.txt
native2ascii -encoding ISO8859-1 zh.txt i.txt
打开i.txt文件,内容为“u00e7u0086u0094u00e5u00b2u00a9”。

D:将zh.txt转换为gbk编码,输出文件到g.txt
native2ascii -encoding gbk zh.txt g.txt
打开g.txt文件,内容为“u9414u65bfu535a”。


E:将u.txt转换为本地编码,输出到文件u_nv.txt
native2ascii -reverse u.txt u_nv.txt
打开u_nv.txt文件,内容为“熔岩”。

F:将u.txt转换为本地编码,输出到控制台
native2ascii -reverse u.txt
可以看到,控制台输出了“熔岩”。

G:将i.txt转码到本地编码,输出到控制台
native2ascii -reverse -encoding ISO8859-1 i.txt
可以看到,控制台输出了“熔岩”。

H:将g.txt转码到本地编码,输出到控制台
native2ascii -reverse -encoding gbk g.txt
可以看到,控制台输出了“熔岩”。

从这个结果看,目标达到到了,编码i.txt为ISO8859-1,转为本地编码后内容为“熔岩”。

从这里应该意识到:

native2ascii -reverse命令中-encoding指定的编码为源文件的编码格式;而在native2ascii 命令中-encoding指定的编码为(生成的)目标文件的编码格式

可以看出,native2ascii是一个将本地编码(可显示内容)和码点(code point)互相转化的工具。

 

原文地址:https://www.cnblogs.com/echo1937/p/6347312.html