首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

关于序列化, unicode和utf编码的有关问题

2013-09-05 
关于序列化, unicode和utf编码的问题本帖最后由 cloudeagle_bupt 于 2013-08-20 19:22:50 编辑1. 编码这些

关于序列化, unicode和utf编码的问题
本帖最后由 cloudeagle_bupt 于 2013-08-20 19:22:50 编辑 1. 编码这些应该是针对字符而言的,整形及数值这些是不需要编码的。因此,无论是硬盘中还是内存中,虽然存的都是二进制码,但是字符的编码方式可以是utf8,unicode等等。

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

参考例子:


 package serial;

import java.io.*;

public class SerialTest {

/**
 * @param args
 * @throws Exception 
 */
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub

Employee e1 = new  Employee( " zhangsan " , 25 , 3000.50 );   
        Employee e2 = new  Employee( " lisi " , 24 , 3200.40 );   
        Employee e3 = new  Employee( " wangwu " , 27 , 3800.55 );   
           
        FileOutputStream fos = new  FileOutputStream("employee.txt");   
        ObjectOutputStream oos = new  ObjectOutputStream(fos);   
        oos.writeObject(e1);   
        oos.writeObject(e2);   
        oos.writeObject(e3);   
        oos.close(); 
        
        FileInputStream fis = new  FileInputStream("employee.txt");   
        ObjectInputStream ois = new  ObjectInputStream(fis);   

        Employee e;   
        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{
String name;   
    int  age;   
    double  salary;
    transient Thread t = new Thread();
    
    
    public  Employee(String name, int  age, double  salary)   
    {   
        this .name = name;   
        this .age = age;   
        this .salary = salary;   
   }   
    
    private   void  writeObject(java.io.ObjectOutputStream oos)  throws  IOException   
    {   
       oos.writeInt(age);   
       oos.writeUTF(name);   
       System.out.println( " Write Object " );   
   }   
    private   void  readObject(java.io.ObjectInputStream ois)  throws  IOException   
    {   
       age = ois.readInt();   
       name = ois.readUTF();   
       System.out.println( " Read Object " );   
   }   
}



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

   private   void  writeObject(java.io.ObjectOutputStream oos)  throws  IOException   
    {   
       oos.writeInt(age);        // 数值型可以直接序列化  
       oos.writeUTF(name);   //将name字符串以utf的编码写入字节流
       System.out.println( " Write Object " );   
   }




  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, 不仅仅是在硬盘上,也可以在内存里这样做。
[解决办法]
关于序列化, unicode和utf编码的有关问题
学习
[解决办法]
关于序列化, unicode和utf编码的有关问题
[解决办法]
关于序列化, unicode和utf编码的有关问题

热点排行