divya patel
divya patel

Reputation: 9

ObjectInputStream is not available

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){

        }

    }
}

The file is not creating while running the code. Code is not executing of try block after FileInputStream. Where is the problem? I tried one solution. File has been created but objectInputStream is not available.

Upvotes: 0

Views: 89

Answers (1)

J_D
J_D

Reputation: 736

After running the code locally, the exception thrown is an EOF exception - java.io.EOFException. A solution would be to do a check to see if the fileInputStream is available:

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

                //out.println("hiii2");

                    hm = (HashMap) objectInputStream.readObject();

            }

Upvotes: 1

Related Questions