关于序列化,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
import java.io.*;
public class SerialTest{
/**
*@paramargs
*@throwsException
*/
public static void main(String[]args) throws Exception{
//TODOAuto-generatedmethodstub
Employeee1= new Employee( "zhangsan" , 25 , 3000.50 );
Employeee2= new Employee( "lisi" , 24 , 3200.40 );
Employeee3= new Employee( "wangwu" , 27 , 3800.55 );
FileOutputStreamfos= new FileOutputStream( "employee.txt" );
ObjectOutputStreamoos= new ObjectOutputStream(fos);
oos.writeObject(e1);
oos.writeObject(e2);
oos.writeObject(e3);
oos.close();
FileInputStreamfis= new FileInputStream( "employee.txt" );
ObjectInputStreamois= new ObjectInputStream(fis);
Employeee;
for ( int i= 0 ;i< 3 ;i++)
{
e=(Employee)ois.readObject();
System.out.println(e.name+ ":" +e.age+ ":" +e.salary);
}
ois.close();
}
}
class Employee implements Serializable{
Stringname;
int age;
double salary;
transient Threadt= new Thread();
public Employee(Stringname, int age, double salary)
{
this .name=name;
this .age=age;
this .salary=salary;
}
private void writeObject(java.io.ObjectOutputStreamoos) throws IOException
{
oos.writeInt(age);
oos.writeUTF(name);
System.out.println( "WriteObject" );
}
private void readObject(java.io.ObjectInputStreamois) throws IOException
{
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码。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值