`
cloudeagle_bupt
  • 浏览: 537556 次
文章分类
社区版块
存档分类
最新评论

关于序列化,utf编码格式和unicode编码

 
阅读更多



1.编码这些应该是针对字符而言的,整形及数值这些是默认二进制编码的。因此,无论是硬盘中还是内存中,虽然存的都是二进制码,但是字符的编码方式可以是utf8,unicode等等。

2.序列化只是一种将对象写入字节流的方法而已。可以自己去定义对象的拆分和组装,对象中的字符,写入字节流时,可以选择编码方式,其他的数值型的话,可以直接按照默认的二进制码进行序列化。


参考例子:

Java code
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
importjava.io.*;
publicclassSerialTest{
/**
*@paramargs
*@throwsException
*/
publicstaticvoidmain(String[]args)throwsException{
//TODOAuto-generatedmethodstub
Employeee1=newEmployee("zhangsan",25,3000.50);
Employeee2=newEmployee("lisi",24,3200.40);
Employeee3=newEmployee("wangwu",27,3800.55);
FileOutputStreamfos=newFileOutputStream("employee.txt");
ObjectOutputStreamoos=newObjectOutputStream(fos);
oos.writeObject(e1);
oos.writeObject(e2);
oos.writeObject(e3);
oos.close();
FileInputStreamfis=newFileInputStream("employee.txt");
ObjectInputStreamois=newObjectInputStream(fis);
Employeee;
for(inti=0;i<3;i++)
{
e=(Employee)ois.readObject();
System.out.println(e.name+":"+e.age+":"+e.salary);
}
ois.close();
}
}
classEmployeeimplementsSerializable{
Stringname;
intage;
doublesalary;
transientThreadt=newThread();
publicEmployee(Stringname,intage,doublesalary)
{
this.name=name;
this.age=age;
this.salary=salary;
}
privatevoidwriteObject(java.io.ObjectOutputStreamoos)throwsIOException
{
oos.writeInt(age);
oos.writeUTF(name);
System.out.println("WriteObject");
}
privatevoidreadObject(java.io.ObjectInputStreamois)throwsIOException
{
age=ois.readInt();
name=ois.readUTF();
System.out.println("ReadObject");
}
}


比如上面这段序列化的代码

privatevoidwriteObject(java.io.ObjectOutputStreamoos)throwsIOException
{
oos.writeInt(age); // 数值型可以直接序列化
oos.writeUTF(name);//将name字符串以utf的编码写入字节流
System.out.println("WriteObject");
}


2. 关于utf编码和unicode的关系,这篇帖子讲的比较清楚:

http://blog.csdn.net/shijinupc/article/details/7679930

http://www.ruanyifeng.com/blog/2007/10/ascii_unicode_and_utf-8.html

个人理解,很多人说utf编码是unicode的一种实现,这样说是没错的,但是实际的文件存储中,也是可以将字符存为不同的编码格式,既可以是unicode, 又可以是utf8, 不仅仅是在硬盘上,也可以在内存里这样做。

PS: 本文请教了rumlee后,纠正了一个错误,这里一般用的数字都是二进制编码,但是也有例外,例如BCD码。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics