简体   繁体   中英

How to determine if a file is empty without getting EOFException

I'm trying to create a file called manager.txt and read it. If it is empty (which it is) it will call a method to add things into it but I keep getting EOFException. I know the file is empty but it's just a part of a programI'm working on. How to determine a file is empty without getting EOFException

try(ObjectOutputStream outManager = new ObjectOutputStream(new 
    FileOutputStream("manager.txt"))){
         try(ObjectInputStream inManager = new ObjectInputStream(new 
             FileInputStream("manager.txt"))){
                 while(true){
                    manager.add((Manager)inManager.readObject());
                    if(manager.isEmpty()){
                      //A method to add
                    }
         }catch(IOException e){

         }
}catch (IOException e){

}

You can read from file as follows:

try (FileInputStream fis = new FileInputStream("manager.txt");
            ObjectInputStream ois = new ObjectInputStream(fis);) 
    {
        while (fis.available() > 0) {
            Object obj = ois.readObject();
            if (obj instanceof Manager) {
                Manager manager = (Manager) obj;
                System.out.println(manager);
            }
        }
    } catch (IOException | ClassNotFoundException ex) {
        ex.printStackTrace();
    }

Basically, what you are looking for is fis.available() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM