对象流

package LESSON12;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Scanner;
class Student implements Serializable{
    private String name;
    private int age;
    public Student(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    
    //写入数据
    public static boolean write(File fileto) throws Exception{
        File parentfile = fileto.getParentFile();
        if(!parentfile.exists()){
            parentfile.mkdirs();
        }
        fileto.createNewFile();
        ArrayList<Student> list = new ArrayList<Student>();
        list.add(new Student("小明", 22));
        list.add(new Student("小芳",23));
        list.add(new Student("小微", 21));
        
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(fileto));
        oos.writeObject(list);
        if(oos!=null){
            oos.close();
            return true;
        }else{
            return false;
        }        
    }
    public static void read(File filefrom) throws Exception{
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filefrom));
        Object obj=ois.readObject();
        ArrayList<Student> stuList=(ArrayList<Student>)obj;
        
        for(Student stu:stuList){
            System.out.println(stu.getName()+"\t"+stu.getAge());
        }
    }    
    public static void copy(File filefrom,File fileto) throws Exception{
        File parentfile = fileto.getParentFile();
        if(!parentfile.exists()){
            parentfile.mkdirs();
        }
        fileto.createNewFile();
        
        FileInputStream fis=new FileInputStream(filefrom);//字节节点输入流
        BufferedInputStream bis=new BufferedInputStream(fis);//字节过滤输入流
        
        FileOutputStream fos=new FileOutputStream(fileto);
        
        int i=bis.read();
        while(i!=-1){
            fos.write(i);
            i=bis.read();
        }        
    }               
}

public class exercise3 {
    /**
    编写java程序,往一个txt文件里写入学生的基本信息,然后再读出这些信息并打印出来
    ,最后把该文件拷贝到指定位置并在文件名前加入日期信息进行备份。
     * @throws Exception 

     */
    public static void main(String[] args) throws Exception {
        System.out.println(Student.write(new File("E:Student.txt")));
        Student.read(new File("E:Student.txt"));
        Student.copy(new File("E:Student.txt"), new File("E:a.txt"));
    }
}

运行结果

posted @ 2019-06-25 19:37  勤奋的园  阅读(174)  评论(0编辑  收藏  举报