Java的对象序列化以及文件IO处理

发表于:2010-9-27 10:58

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:未知    来源:51Testing软件测试网采编

分享:

  以下是一个对象序列化,反序列化以及文件IO的例子,以后可以翻阅

class CashCheck implements Serializable
{
 private static final long serialVersionUID = -8872155900725314694L;

 private String cashCheckID;

 private int cashAmout;

 public CashCheck()
 {
 }

 public String getCashCheckID()
 {
  return cashCheckID;
 }

 public void setCashCheckID(String cashCheckID)
 {
  this.cashCheckID = cashCheckID;
 }

 public int getCashAmout()
 {
  return cashAmout;
 }

 public void setCashAmout(int cashAmout)
 {
  this.cashAmout = cashAmout;
 }
}

public class SerializeDemo01
{
 public static void main(String[] args)
 {
  CashCheck check = new CashCheck();
  check.setCashAmout(10000);
  check.setCashCheckID("notifier");

  /*
   * 序列化对象
   */
  try
  {
   // 1.创建文件输出流,负责将字节写入文件
   FileOutputStream fs = new FileOutputStream(
     new File(
       "C:\\Documents and Settings\\Administrator\\桌面\\notifier.file"));

   // 2.创建对象输出流,负责将对象转为字节
   ObjectOutputStream os = new ObjectOutputStream(fs);

   // 3.写入对象
   os.writeObject(check);

   // 4.关闭对象输出流
   os.close();
  } catch (FileNotFoundException e)
  {
   e.printStackTrace();
  } catch (IOException e)
  {
   e.printStackTrace();
  }

  /*
   * 解序列化对象
   */
  try
  {
   // 1.创建文件输入流,负责将文件转为字节
   FileInputStream fi = new FileInputStream(
     "C:\\Documents and Settings\\Administrator\\桌面\\notifier.file");

   // 2.创建对象输入流,负责将字节写入对象
   ObjectInputStream oi = new ObjectInputStream(fi);

   // 3.读出对象
   Object o1 = oi.readObject();
   if (o1 instanceof CashCheck)
   {
    CashCheck check1 = (CashCheck) o1;
    System.out.println(check1.getCashCheckID());
    System.out.println(check1.getCashAmout());
   }

   // 4.关闭对象输入流
   oi.close();
  } catch (FileNotFoundException e)
  {
   e.printStackTrace();
  } catch (IOException e)
  {
   e.printStackTrace();
  } catch (ClassNotFoundException e)
  {
   e.printStackTrace();
  }

  /*
   * 以文件的形式读出序列化文件,是乱码
   */
  try
  {
   FileReader fr = new FileReader(
     new File(
       "C:\\Documents and Settings\\Administrator\\桌面\\notifier.file"));
   BufferedReader br = new BufferedReader(fr);

   String line = null;
   while ((line = br.readLine()) != null)
   {
    System.out.println(line);
   }
  } catch (FileNotFoundException e)
  {
   e.printStackTrace();
  } catch (IOException e)
  {
   e.printStackTrace();
  }
 }
}

33/3<123
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号