日期:2014-05-20  浏览次数:20838 次

ObjectInputStream 判断文件结束
ObjectInputStream 如何判断.dat文件结束啊??

------解决方案--------------------
Java code

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

import com.kevinb.io.bean.User;

public class ObjectOutputStreamModel {

    private static void writeObjectFile(){
        String sourceFile = "src/com/kevinb/io/objectStream/userFile";
        File file = new File(sourceFile);
        try {
            FileOutputStream fiOutputStream = new FileOutputStream(file);
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(fiOutputStream);
            //开始准备插入对象
            User user1 = new User();
            user1.setUserId(1);
            user1.setUserName("Kevinb");
            user1.setPassword("ffffff");
            objectOutputStream.writeObject(user1);
            
            User user2 = new User();
            user2.setUserId(2);
            user2.setUserName("Jone");
            user2.setPassword("11");
            objectOutputStream.writeObject(user2);
            
            //写入结束标志方便读取(非常重要,如果不写入,在读取的时候无法定位读取结束);
            objectOutputStream.writeObject(null);
            //close outputStream
            objectOutputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("对象写入成功!");
    }
    
    public static void main(String[] args) {
        writeObjectFile();
    }
}