java.io.EOFException异常处理

在读取文件中对象时遇到java.io.EOFException异常 

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;

public class ReadFromFile {

    public static ArrayList readFromFile() {
        ObjectInputStream ois = null;
        File f = new File ("d:\\student.txt");
        ArrayList st = new ArrayList ( );
        try {
            FileInputStream fis = new FileInputStream (f);
            //文件不存在创建文件
            if (!f.exists ( )) {
                f.createNewFile ( );
            }
            ois = new ObjectInputStream (fis);
            Student[] students = (Student[]) ois.readObject ( );
            for (Student s : students
            ) {
                // System.out.println (s );
                st.add (s);
            }
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace ( );
        } finally {
            if (null != ois) {
                try {
                    ois.close ( );
                } catch (IOException e) {
                    e.printStackTrace ( );
                }
            }
        }
        return st;
    }

}

异常原因:因文件为空,输入流未读取到任何数据

解决方法:加判断条件,如果文件大小为0 则不读取文件内容,增加代码如下:

 if (f.length ( ) == 0) {
                fis.close ();
                return st;
            } else {
                ois = new ObjectInputStream (fis);
            }

 

你可能感兴趣的:(java)