猿问

初学者请教关于java编码的问题

很简答的的示例程序,大家看下

我的问题是,我不明白,文件的明明是0-50000这些数字,为什么文件打开以后,里面是各种各样的符号呢,有中文,英文,日文等等各种字符。
我能知道是unicode编码的原因,但是不是很清楚原理
请各位帮忙解释下,或者给个详细解释这个的链接之类的更好。

非常感谢!


米琪卡哇伊
浏览 444回答 3
3回答

慕码人8056858

我来尝试回答一下,现学现卖 ^_^ (我使用 linux 可能不大一样)先看文档中文,它有五个方法/**&nbsp;* write(String str)&nbsp;* 写入字符串。&nbsp;* write(int oneChar)&nbsp;* 写入单个字符。要写入的字符包含在给定整数值的 16 个低位中,16 高位被忽略。用于支持高效单字符输出的子类应重写此方法。&nbsp;&nbsp;* write(char[] buf)&nbsp;* 写入字符数组&nbsp;* write(String str, int offset, int count)&nbsp;* write(char[] buf, int offset, int count)&nbsp;*/用的是 write(int oneChar) 这一种,写入单个字符表,用计算器高位被忽略就是&nbsp; 00000000|00110010&nbsp; &nbsp;//501|00000000|00110010&nbsp; &nbsp;//65536 + 50-------------------然后两者其实结果是一样的。过程如下,只看最后两段即可import java.io.FileWriter;/**&nbsp;* Created by star on 11/29/13.&nbsp;* write(char[] buf, int offset, int count)&nbsp;* write(String str)&nbsp;* write(int oneChar)&nbsp;* write(char[] buf)&nbsp;* write(String str, int offset, int count)&nbsp;*/public class Encode {&nbsp; &nbsp; public static void main (String [] args) {&nbsp; &nbsp; &nbsp; &nbsp; FileWriter fw = null;&nbsp; &nbsp; &nbsp; &nbsp; try {//&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; *输出字符串"妳好"//&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fw = new FileWriter("/home/star/unicode.txt");//&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; String a = "妳好";//&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fw.write(a);//&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fw.close();//&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; *这里打印的不是50,而是50的16进制所代表的值「2」//&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fw = new FileWriter("/home/star/unicode.txt");//&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; int a = 50;//&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fw.write(a);//&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fw.close();//&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; *比16位高的位数被忽略。会打印相同的两个「2」//&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fw = new FileWriter("/home/star/unicode.txt");//&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fw.write(50);//&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fw.flush();//&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fw.write(65536 +50);//&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fw.flush();//&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fw.close();//&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; *我想你要的结果是这样的吧 0x4e00 开始&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fw = new FileWriter("/home/star/unicode.txt");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for (int a = 19968 ; a<19968 + 500;a++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fw.write(a);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fw.close();&nbsp; &nbsp; &nbsp; &nbsp; } catch (Exception e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; e.printStackTrace();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println("文件写入错误");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.exit(-1);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}
随时随地看视频慕课网APP

相关分类

Java
我要回答