1) 用包装类进行数据传输
package IO;
import java.io.*;
public class DataStreamTest {
public static void main(String[] args) throws Exception{
FileOutputStream fos=new FileOutputStream("count.txt");//定义一个文件写入流
BufferedOutputStream bos=new BufferedOutputStream(fos);//用缓冲类包装文件写入流
DataOutputStream dos=new DataOutputStream(bos);//用包装类包装缓冲类
dos.writeUTF("ab中国");//用utf格式向文件中写入信息
dos.writeBytes("ab中国");
dos.writeChars("ab中国");
dos.close();//关闭文件输入流
FileInputStream fis=new FileInputStream("count.txt");//定义一个文件输出流
BufferedInputStream bis=new BufferedInputStream(fis);
DataInputStream dis=new DataInputStream(bis);
System.out.println(dis.readUTF());//以utf格式读取数据流
byte []buf=new byte[1024];
int len=dis.read(buf);
System.out.println(new String(buf,0,len));
dis.close();
}
}
2)ObjectOutputStream和ObjectInputStream包装类的学习
package IO;
import java.io.*;
public class Serialization {
public static void main(String[] args) throws Exception {
Student stu1=new Student(19,"张三",25,"化学");//定义对象
Student stu2=new Student(20,"李四",23,"物理");
FileOutputStream fos=new FileOutputStream("student.txt");//定义输出流
ObjectOutputStream os=new ObjectOutputStream(fos);//包装输出流,为对象的输出
os.writeObject(stu1);//写入对象
os.writeObject(stu2);
os.close();//关闭输出流
FileInputStream fis=new FileInputStream("student.txt");//定义输入流,读取文件
ObjectInputStream is=new ObjectInputStream(fis);//定义输入类型为对象输入
stu1=(Student)is.readObject();//用对象接收数据
stu2=(Student)is.readObject();
is.close();
System.out.println("id:"+stu1.id);//打印对象信息
System.out.println("name:"+stu1.name);
System.out.println("age:"+stu1.age);
System.out.println("department:"+stu1.department+"/n");
System.out.println("id:"+stu2.id);
System.out.println("name:"+stu2.name);
System.out.println("age:"+stu2.age);
System.out.println("department:"+stu2.department);
}
}