0、对象序列化的类一定要实现Serializable接口,下面是一个很简单的例子:代码可以运行。
class Person implements Serializable{
private String name;
private int age; // 如果不想序列化age,就这样写private transient int age ;就不会被序列化了。
public Person(String name,int age){
this.name=name;
this.age=age;
}
public String toString(){
return "姓名:"+this.name+" 年龄:"+this.age;
}
}public class TestPerson {
public static void main(String[] args)throws Exception{
//创建要序列化的对象
Person p=new Person("jack",25);
per(p);
System.out.println("已成功的序列化!!!");
//Perc(p)是要输出的序列化的结果!
perc(p);
}
//写入对象序列化
public static void per(Person per)throws Exception{
ObjectOutputStream os=new ObjectOutputStream(new FileOutputStream(new File("d:\jackPerson.txt")));
os.writeObject(per);
}
//读出对象序列化
public static void perc(Person pe)throws Exception{
ObjectInputStream oss=new ObjectInputStream(new FileInputStream(new File("d:\jackPerson.txt")));
Object o=oss.readObject();
System.out.println(o);
}
}
1、下面是字符流的操作
读文件:
File read = new File("c:\1.txt");
BufferedReader br = new BufferedReader(
new FileReader(read));
System.out.println(br.readLine());
br.close();
写文件:
File write = new File("c:\2.txt");
BufferedWriter bw = new BufferedWriter(
new FileWriter(write)); bw.write("ni");
bw.write("ni");
bw.close();
=======================================================
2、下面是字节流的操作
//字节流的写入
import java.io.*;
public class TestOutS{
public static void main(String[] args)throws Exception{
File f=new File("d:\jack.txt");
OutputStream ops=new FileOutputStream(f);
String s="jack 123";
byte[] b=s.getBytes(); ops.write(b);
ops.close();
System.out.println("成功写入!");
}
}
//字节流的读出
import java.io.*;
public class TestInS{
public static void main(String[] args)throws Exception{
File f=new File("d:\jack.txt");
InputStream ips=new FileInputStream(f);
byte[] b=new byte[3000];
int len=0;
len=ips.read(b);
System.out.println(new String(b,0,len));
}
}
============================================================
3、序列化与反序列化的用法。
file = new File(“C:/data.dat”);
oos = new ObjectOutputStream(new FileOutputStream(file));
ois = new ObjectInputStream(new FileInputStream(file));
下面是自己写的代码可以运行!
public class TestZJ {
public static void main(String[] args)throws Exception{ File f=new File("d://test1.txt");
FileOutputStream fs=new FileOutputStream(f);
ObjectOutputStream os=new ObjectOutputStream(fs);
String s="我是一个中国人!!!";
os.writeObject(s);
os.close();
System.out.println("可以成功的写到磁盘上!!!");
File f2=new File("d://test1.txt");
FileInputStream fs2 = new FileInputStream(f2);
ObjectInputStream os2 = new ObjectInputStream(fs2);
Object bs = os2.readObject();
System.out.println(bs);
System.out.println("可以成功的读出来!!!");
}
}
或者网络流通道
oos = new ObjectOutputStream(socket.getOutputStream());
ois = new ObjectInputStream(socket.getInputStream());
下面是:字符流和字节流的区别,使用场景,相关类 的网站
http://weijinliang.blog.51cto.com/521552/147514