Java中的反序列化无法在多种方法中一致地工作

时间:2018-09-11 03:32:35

标签: java file

在Windows中创建FileInputStream时出现错误 deletebook()方法。但是相同的对象创建在 searchBook()方法。没有人知道为什么当唯一不同的是传递给方法的参数时,代码会产生不同的结果吗?

import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class TestMain {
    public static final String FILENAME = "cool_file.txt";
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        // TODO Auto-generated method stub
        FileOutputStream fos = null;
        fos = new FileOutputStream(FILENAME);
        System.out.println("Welcome to the Application");
        ObjectOutputStream oos1;
        int sel = 0;
        TestMain t = new TestMain();
        do {
            System.out.println("1) addSubject");
            System.out.println("2) addBook");
            System.out.println("3) deleteSubject");
            System.out.println("4) deleteBook");
            System.out.println("5) searchBook");
            System.out.println("6) searchSubject");
            System.out.println("7) Exit");
            System.out.println("#############");
            System.out.println("Insert a selection");
            Scanner s = new Scanner(System.in);
            sel = s.nextInt();

            switch (sel) {
            case 1:
                t.addSubject();
                break;
            case 2:
                t.addBook(fos);
                break;
            case 3:
                t.deleteSubject();
                break;
            case 4:
                t.deleteBook(fos);
                break;
            case 5:
                t.searchBook();
                break;
            case 6:
                t.searchSubject();
                break;
            case 7:
                t.exitService();
                break;
            default:
                System.out.println("Invalid Selection");
            }

        } while (sel != 7);

    }

    public void addSubject() {
        System.out.println("In addSubject"+"\n");
        }

    public void addBook(FileOutputStream fos) throws IOException {
        System.out.println("In addBook"+"\n");
        long bookId;
        String title;
        double price;
        Integer volume;
        LocalDate publishDate;
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        System.out.println("Enter Book ID");
        Book b=new Book();
        Scanner s=new Scanner(System.in);
        bookId=s.nextLong();
        System.out.println("Enter the Title of the Book");
        title=s.next();
        System.out.println("Enter the price of the Book");
        price=s.nextDouble();
        System.out.println("Enter the Volume of the Book");
        volume=s.nextInt();
        System.out.println("Enter the publishDate of the Book");
        String dateStr_1=s.next();
           DateTimeFormatter formatter_1=DateTimeFormatter.ofPattern("dd-MM-yyyy");
            publishDate= LocalDate.parse(dateStr_1,formatter_1);
            b.setBookId(bookId);
            b.setTitle(title);
            b.setPrice(price);
            b.setVolume(volume);
            b.setPublishDate(publishDate);

            oos.writeObject(b);
            //fos.close();
            //oos.close();

    }


    public void deleteSubject() {
        System.out.println("In deleteSubject"+"\n");
    }

    public void deleteBook(FileOutputStream fos) throws IOException, ClassNotFoundException {
        System.out.println("In deleteBook"+"\n");
        System.out.println("Enter the Book Id to be deleted");
        Scanner s=new Scanner(System.in);
        int bookId=s.nextInt();
        ArrayList<Book> results = new ArrayList<Book>();

        FileInputStream fis = null;
        System.out.println(fis);
        try {
            fis = new FileInputStream(FILENAME);
            System.out.println(fis);
            while (true) {
                ObjectInputStream ois = new ObjectInputStream(fis);
                results.add((Book) ois.readObject());
            }
        } catch (EOFException ignored) {
            ignored.printStackTrace();
            // as expected
        } finally {
            if (fis != null)
                fis.close();
            System.out.println("Finally");
        }
        System.out.println("results = " + results);
        for(Book b:results)
        {
        if(b.getBookId()==bookId)   
        {
            results.remove(b);
        }
        }

        File file = new File(FILENAME);

        if(file.exists())
        {
            file.delete();
            System.out.println("File Exists");
            if(file.exists())
                {
                System.out.println("File Exists after deletion");
            }
        }
            if(file.delete())
        {
            System.out.println("File deleted successfully");
        }
        else
        {
            System.out.println("Failed to delete the file");
        }

        /*ObjectOutputStream oos = new ObjectOutputStream(fos);
        for(Book newb:results)
        oos.writeObject(newb);*/


    }
    public void searchBook() throws ClassNotFoundException, IOException {
        System.out.println("In searchBook"+"\n");
         ArrayList<Book> results = new ArrayList<Book>();

            FileInputStream fis = null;
            try {
                fis = new FileInputStream(FILENAME);
                while (true) {
                    ObjectInputStream ois = new ObjectInputStream(fis);
                    results.add((Book) ois.readObject());
                }
            } catch (EOFException ignored) {
                // as expected
            } finally {
                if (fis != null)
                    fis.close();
            }
            System.out.println("results = " + results);

    }
    public void searchSubject() {
        System.out.println("In searchSubject"+"\n");

    }
    public void exitService() {
        System.out.println("Thank You for using the service..You rare now Exitinng the service");

    }
}
  

这是控制台:

     

欢迎来到应用程序1)addSubject 2)addBook 3)deleteSubject   4)deleteBook 5)searchBook 6)searchSubject 7)退出

     #######在addBook中插入选择2      

输入图书ID 1输入图书标题ufihv输入价格   书籍1输入书籍的体积1输入书籍的出版日期   图书01-01-2001 1)addSubject 2)addBook 3)deleteSubject 4)   deleteBook 5)searchBook 6)searchSubject 7)退出

     #######在addBook中插入选择2      

输入书籍ID 2输入书籍的标题2输入书籍的价格   图书2输入图书的体积2输入图书的发布日期   图书02-02-2002 1)addSubject 2)addBook 3)deleteSubject 4)   deleteBook 5)searchBook 6)searchSubject 7)退出

     #######插入选择4在deleteBook中      

输入要删除的图书ID 1空   java.io.FileInputStream@7106e68e java.io.EOFException最终结果   = [Book @ 1a6c5a9e,Book @ 37bba400]文件存在删除后文件存在删除文件失败1)addSubject 2)addBook 3)   deleteSubject 4)deleteBook 5)searchBook 6)searchSubject 7)退出

     #######在java.io.ObjectInputStream $ PeekInputStream.readFully插入选择(未知源)      

at java.io.ObjectInputStream $ BlockDataInputStream.readShort(未知   源)位于java.io.ObjectInputStream.readStreamHeader(未知源)     在java.io.ObjectInputStream(未知来源)在   TestMain.deleteBook(TestMain.java:124)在   TestMain.main(TestMain.java:49)

1 个答案:

答案 0 :(得分:0)

我不太确定,为什么要删除具有对象可序列化状态的文件。因此,当您删除文件时,该文件具有对象的可序列化状态。您将丢失所有内容,即使文件不存在。而且,如果您尝试通过其他方法访问同一文件,则会出现异常。

此外,删除特定对象时,不会将对象的最新更新状态保存到文件中(未序列化对象的最新状态),而是直接删除了文件。那么,从反序列化对象中删除对象有什么意义呢?