StochasticNerd StochasticNerd - 22 days ago 11
Java Question

EOFException in Spring REST

So I have DataStructure that I want to persist in my Spring REST application.
This is how I'm initializing the

@bean


@Configuration
public class MessageBrokerInitializer {

@Bean
public MessageBroker getMessageBroker(){

FileInputStream fileInputStream;
ObjectInputStream objectInputStream;
MessageBroker broker = null;
try {
fileInputStream = new FileInputStream("./data/store.ser");
objectInputStream = new ObjectInputStream(fileInputStream);
broker = (MessageBroker) objectInputStream.readObject();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}

return (broker == null) ? new MessageBroker(): broker;
}



}


Basically I'm trying to read a file initialize my object or if the file is empty I want to new up the data structure. I keep getting,

java.io.EOFException


How can I get this working.

Answer

You can avoid EOFException by checking objectInputStream.available() for the number of bytes that can be read as shown below:

@Configuration
public class MessageBrokerInitializer {

    @Bean
    public MessageBroker getMessageBroker(){

        FileInputStream fileInputStream;
        ObjectInputStream objectInputStream;
        MessageBroker broker = null;
        try {
            fileInputStream = new FileInputStream("./data/store.ser");

            if(fileInputStream.available() != 0) {
              objectInputStream = new ObjectInputStream(fileInputStream);
              broker = (MessageBroker) objectInputStream.readObject();
            } else {
              broker = new MessageBroker()
           }               
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return broker;
    }
}

You can look here

Comments