1

As an exercise, I am creating a list of Books as a LinkedList and using the Comparator interface to sort them by author or title. First, I create a class of books and ensure that it will print to screen the way I want it to:

class Book {
    String title;
    String author;
    public Book(String t, String a){
        title = t;
        author = a;
    }
    public String toString(){
        return title + "\t" + author;
    }
}

Next, I created a LinkedList that takes Object Book:

LinkedList<Book> bookList = new LinkedList<>();

A class that implements Comparator is created that sorts according to title/author and displays them on a JTextArea inside of my main frame. All of that is working just fine, but there's one glaring bug...I cannot save the file!

I've tried a class that implements Serializable that takes the LinkedList as a argument and then writes a .obj file. When I load it, it fails. It creates the file, but I usually get a NotSerializableException. I also tried saving the file as .ser as I was told that this could make it easier to save it, but this failed on loading, as well.

Does anyone know a good method for serializing a LinkedList using a BufferedReader? Or is there another approach to this? Thank you in advance for your time reading through this question, and also thank you for any advice, comments, or answers that you can provide. Thanks, guys.

Addition: This is the entire code:

import javax.swing.*;
import java.util.*;
import java.awt.event.*;
import java.awt.*;
import java.io.*;

public class Check {

    BookCompare bc = new BookCompare();
    LinkedList<Book> bookList = new LinkedList<>();
    JFrame frame;
    JPanel northPanel, centerPanel, southPanel;
    JButton addBook, saveBook, loadBook;
    JTextField authorField, titleField;
    JTextArea displayBook;

    public static void main(String[] args) {
        new Check().buildGui();
    }

    private void buildGui() {
        frame = new JFrame("Book List");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        northPanel = new JPanel();
        centerPanel = new JPanel();
        southPanel = new JPanel();

        addBook = new JButton("Add Book");
        addBook.addActionListener(new AddButton());
        saveBook = new JButton("Save List");
        saveBook.addActionListener(new SaveButton());
        loadBook = new JButton("Load List");
        loadBook.addActionListener(new LoadButton());

        JLabel authorL = new JLabel("Author:");
        authorField = new JTextField(10);
        JLabel titleL = new JLabel("Title:");
        titleField = new JTextField(10);

        displayBook = new JTextArea(20,40);
        displayBook.setEditable(false);
        JScrollPane scroll = new JScrollPane(displayBook);
        scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);

        northPanel.add(titleL);
        northPanel.add(titleField);
        northPanel.add(authorL);
        northPanel.add(authorField);
        centerPanel.add(scroll);
        southPanel.add(addBook);
        southPanel.add(saveBook);
        southPanel.add(loadBook);

        frame.getContentPane().add(BorderLayout.NORTH,northPanel);
        frame.getContentPane().add(BorderLayout.CENTER,centerPanel);
        frame.getContentPane().add(BorderLayout.SOUTH,southPanel);

        frame.setVisible(true);
        frame.setSize(500, 500);
        frame.setResizable(false);
        frame.setLocation(375, 50);
    }

    class AddButton implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            addToList();
            sortAndDisplay();
            readyNext();
        }
    }

    private void addToList() {
        String newTitle = titleField.getText();
        String newAuthor = authorField.getText();
        bookList.add(new Book(newTitle, newAuthor));
    }

    private void sortAndDisplay() {
        displayBook.setText(null);
        Collections.sort(bookList,bc);
        for(int i = 0; i < bookList.size(); i++){
            displayBook.append(bookList.get(i).toString());
        }
    }

    private void readyNext() {
        authorField.setText(null);
        titleField.setText(null);
        titleField.requestFocus();
    }

    class SaveButton implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            try {
                ObjectOutputStream oo = new ObjectOutputStream(new FileOutputStream("save.ser"));
                oo.writeObject(bookList);
                oo.close();
            } catch (IOException ioe){}
        }
    }

    class LoadButton implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            try {
                ObjectInputStream oi = new ObjectInputStream(new FileInputStream("save.ser"));
                Object booksIn = oi.readObject();
                Book inBook = (Book)booksIn;
                bookList.add(inBook);
                sortAndDisplay();
                oi.close();
            } catch (Exception exc){}
        }
    }

    class BookCompare implements Comparator<Book> {
        public int compare(Book one, Book two) {
            return one.title.compareTo(two.title);
        }
    }

    class Book implements Serializable{
        String title;
        String author;
        public Book(String t, String a) {
            title = t;
            author = a;
        }
        public String toString(){
            return title + "\t" + author + "\n";
        }
    }
}

Get a error list after validate xml against a schema file

I´m validating a XML file against a schema xsd. So far so good, the code generates a exception in case of failure.

        bool isValid = true;
        List<string> errorList = new List<string>();
        try
        {
            XmlReaderSettings settings = new XmlReaderSettings();
            settings.Schemas.Add(null, schemaFilePath);
            settings.ValidationType = ValidationType.Schema;
            XmlDocument document = new XmlDocument();
            document.LoadXml(xml);
            XmlReader rdr = XmlReader.Create(new StringReader(document.InnerXml), settings);
            while (rdr.Read()) { }
        }
        catch (Exception ex)
        {
            errorList.Add(ex.Message);
            isValid = false;
        }

        LogErrors(errorList);
        return isValid;

But I need that the code build a list of all errors found in the validate before send it to my log, instead of always show only the first one found.

Any thoughts?

4

1 回答 1

4

让你的 Book 课Serializable像这样

class Book implements Serializable{
  String title;
  String author;
  public Book(String t, String a){
     title = t;
     author = a;
  }
  public String toString(){
     return title + "\t" + author;
  }
}

序列化接口没有方法或字段,仅用于识别可序列化的语义。因此您无需实现任何方法,只需声明即可。
根据java文档

类的可序列化性由实现 java.io.Serializable 接口的类启用。未实现此接口的类将不会对其任何状态进行序列化或反序列化。可序列化类的所有子类型本身都是可序列化的。序列化接口没有方法或字段,仅用于识别可序列化的语义。

更新以解决当前问题
您错误地实施了反序列化过程。这是正确的实施。试试这个你会得到想要的结果。

class LoadButton implements ActionListener {
    public void actionPerformed(ActionEvent e) {
        try {
            ObjectInputStream oi = new ObjectInputStream(new FileInputStream("save.ser"));
            Object booksIn = oi.readObject();
            bookList = (LinkedList<Book>)booksIn;
            sortAndDisplay();
            oi.close();
        } catch (Exception exc){}
    }
 }
于 2013-08-07T19:08:01.880 回答