ObjectInputStream不可用

时间:2017-09-21 19:59:15

标签: java

public class MakeNewFile{
    static HashMap<String, User> hm = new HashMap<String, User>();

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.out.println("Hello!!");
        try{
            File inputFile = new File("C:\\apache-tomcat-7.0.34\\webapps\\products\\Details.txt");  
            System.out.println("Done");
            boolean resut = inputFile.createNewFile();
            System.out.println(resut);
            System.out.println("File found");           
            //fileInputStream = new FileInputStream(inputFile);                                 
            FileInputStream fileInputStream = new FileInputStream(inputFile);
            ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
            //out.println("hiii2");
            hm= (HashMap)objectInputStream.readObject();
            System.out.println("hiii" +hm);

            if(hm.containsKey("username"))
                { String error_msg = "Username already exist as " + "usertype";}
            else{
                User user = new User("firstname", "lastname", "email", "username","password","usertype");
                hm.put("username", user);
                FileOutputStream fileOutputStream = new FileOutputStream("C:\\apache-tomcat-7.0.34\\webapps\\products\\Details.txt");
                ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
                objectOutputStream.writeObject(hm);
                objectOutputStream.flush();
                objectOutputStream.close();
                fileOutputStream.close();

            }
        }
        catch(Exception ex){

        }

    }
}

运行代码时文件未创建。代码未在try之后执行FileInputStream阻止。问题出在哪儿? 我试过一个解决方案。文件已创建,但objectInputStream不可用。

1 个答案:

答案 0 :(得分:1)

在本地运行代码后,抛出的异常是EOF异常 - java.io.EOFException。解决方案是检查fileInputStream是否可用:

if (fileInputStream.available() > 0) {
                ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);

                //out.println("hiii2");

                    hm = (HashMap) objectInputStream.readObject();

            }