[java]关于IO文件代码读取的注意事项

本文介绍如何使用Java的ObjectOutputStream和ObjectInputStream实现对象的序列化和反序列化过程。通过具体示例,演示了如何将一个包含多个属性的对象写入文件,并从文件中读取回来。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 IO读取是相对严格的,一般通过相应的outputstream写入的数值,必须通过相对应的InputStream来读取,否则数值是不对的,也就是显示是乱码或者错误的。譬如我们用ObjectOutputStream写入一段数据到一个test.txt的文件中,写入的数值是二进制的,用记事本打开可能看不出什么名堂,我们可以利用UtrlEdit查看对应的二进制代码,其实呢,还是没不懂啥意思,哈哈,因此我们必须用ObjectInputStream来读取test.txt中的数据,否则就会出错。

下面是一段演示代码: Serializatiom.java

 

import java.io.*;

/**
 * 序列化对象输入输出
 
*/

 
 
public class Serialization 
 
{
     
public static void main(String[] args) throws IOException,ClassNotFoundException
     
{
         Student stu 
= new Student(19,"MiLdo",24,"中国特警队"); //Student的构函是带参数的。
         FileOutputStream fos = new FileOutputStream("d:/java/Serialization.txt");
         ObjectOutputStream oop 
= new ObjectOutputStream(fos);
         
try
         
{
             oop.writeObject(stu);
             oop.close();
         }

         
catch(IOException e)
         
{
             System.out.println(e.getMessage());
         }

         
         stu 
= null;
         FileInputStream fis 
= new FileInputStream("d:/java/Serialization.txt");
         ObjectInputStream ois 
= new ObjectInputStream(fis);
         
try
         
{
             stu 
= (Student)ois.readObject(); //时时不忘类型转换。
             ois.close();  //时时不忘关闭流对象
         }

         
catch(IOException e)
         
{
             System.out.println(e.getMessage());
         }

         System.out.println(
"student id = "+stu.id);
         System.out.println(
"student name = "+ stu.name);
         System.out.println(
"student age = "+ stu.age);
         System.out.println(
"student department = "+stu.department);
     }

     
 }

 
 
class Student implements Serializable
 
{
     
int id;
     String name;
     
int age;
     String department;
     
     
public Student(int id,String name,int age,String department)
     
{
         
this.id = id;
         
this.name = name;
         
this.age = age;
         
this.department = department;
     }

 }

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值