JAVA 22 IO 中其他对象

对象的持久化
操作对象的字节流,被操作的对象要实现Serializable接口。但不需要复写方法,只是一个标记接口。
 
 
ObjectOutputStream
除了从InputStream继承的基本方法外,特性方法介绍。
1,构造方法
    空
    ObjectOutputStream(OutputStream);//指定输出位置。
2,
    writeInt()
    writeFloat() 等等
    writeObject();写入一个对象。
 
ObjectInputStream
1,构造方法
    空
    ObjectIntputStream(IntputStream);//指定读取对象文件位置
2,
    Object readObject(); 一次读取一个对象。需要强制类型转换。
区别不同类的方式是根据成员计算出一个uid,不同的uid对应不同的对象
也可以自己定义uid,当对象实现了Serializable接口后,可以通过以下语句设定。
public static final long serialVersionUID = 42L;
 
静态数据是不能序列化的,即不能写入文件中,写入的只是默认值。
对非静态成员也可以不被序列化,只需要
transient int age ;
 
管道流:
输入输入可直接连接进行,通过合并线程完成。
其中输入管道和输出管道应该在两个线程中。
PipedInputStream 
PipedOutPutStream
 
创建的时候直接连接。
PipedInputStream (new PipedInputStream())
PipedOutPutStream(new PipedInputStream ())
也可以同个connect()方法来连接。连接一次即可。
 
RandomAccessFile//随机访问文件类。可读可写
DataStream //操作基本数据类型的
ByteArrayStream//操作数组
 
ObjectInputStream 和 ObjectOutputStream 举例应用
import java.io.*;
import java.util.*;
 
public class Test {
 
 public static void main(String[] args) throws IOException, ClassNotFoundException
 {
  //ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("C:\\Users\\zx\\Desktop\\第21天\\File.txt"));
  //oos.writeObject(new Persion(23,"zhangxu"));//写入Persion对象到文件中
  ObjectInputStream ois = new ObjectInputStream(new FileInputStream("C:\\Users\\zx\\Desktop\\第21天\\File.txt"));
  Persion p =(Persion) ois.readObject();//读取对象
  sop(p.age+"..."+p.name);
    oos.close();
    ois.close()
 }  
 public static void sop(Object o)  
 {
  System.out.println(o);
 }
}
class Persion implements Serializable
{
 String name;
 int age;
 Persion(int age,String name)
 {
  this.age=age;
  this.name=name;
 }
}
 
管道流举例:
import java.io.*;
import java.util.*;
 
public class Test {
 
 public static void main(String[] args) throws IOException
 {
  PipedInputStream in = new PipedInputStream();
  PipedOutputStream out = new PipedOutputStream();
  in.connect(out);
  Read r = new Read(in);
  Write w = new Write(out);
  new Thread(r).start();
  new Thread(w).start();
 }
 public static void s(Object o)
 {
  System.out.println(o);
 }
}
class Read implements Runnable
{
 private PipedInputStream in;
 Read(PipedInputStream in)
 {
  this.in=in;
 }
 public void run()
 {
  try
  {
  byte[] buf = new byte[1024];
  int len = in.read(buf);
  String s = new String(buf,0,len);
  System.out.println(s);
  in.close();
  }
  catch(IOException e)
  {
   
  }
 
 }
}
class Write implements Runnable
{
 private PipedOutputStream out;
 Write(PipedOutputStream out)
 {
  this.out=out;
 }
 public void run()
 {
  try
  {
   Thread.sleep(6000);
  out.write("laila".getBytes());
  }
  catch(IOException e)
  {
  }
  catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
 
}

 

posted @ 2015-09-30 16:47  hitz&x  阅读(123)  评论(0编辑  收藏  举报