如何在java中将ArrayList对象写入文本文件

时间:2014-11-27 11:00:25

标签: java arraylist

我正在尝试将Arraylist输出到text.file,arraylist有两个对象,librarybook和book。如何将2个对象打印到text.file中? 写text.file有4个类。谢谢你的帮助!

class Book {
    // Declare data members
    protected int bookID;
    protected String bookName;
    protected boolean isAvailable;
    private int borrowerID;
    public static int totalNoOfBook = 0;
    public static int totalNoOfAvailableBook = 0;

    // Constructor
    private Book() {
        // initialization
        bookName = "";
        isAvailable = true;
        totalNoOfAvailableBook++;
    }

    public Book(String name) {
        this();
        // initialization
        bookID = totalNoOfBook;
        bookName = name;
        totalNoOfBook++;
    }

    // Methods
    // Borrow a book
    public void borrow(LibraryCard card) {
        isAvailable = false;
        borrowerID = card.getCardID();
        card.incrementBorrowedNum();
        totalNoOfAvailableBook--;
    }

    // Print the book information
    public void printAvailableBookInfo() {
        if (isAvailable) {
            System.out.println("----------------------------------------------------------");
            System.out.println("                         Book                             ");
            System.out.println("----------------------------------------------------------");
            System.out.println("Book ID \t: " + bookID);
            System.out.println("Book name \t: " + bookName);
            System.out.println("----------------------------------------------------------\n");
        }
    }
}

这是子类。

public class LibraryBook extends Book   // subclass
{
    private String author;
    private int year;
    public int TotalofBook = 0;

    public LibraryBook(String name, String bk_Au, int bk_Ye) {
        super(name);
        author = bk_Au;
        year = bk_Ye;
    }


    public String getAuthor() {
        return author;
    }

    public int getYear() {
        return year;
    }

    public void printAvailableBookInfo() {
        if (isAvailable) {
            System.out.println("----------------------------------------------------------");
            System.out.println("                     LibraryBook                          ");
            System.out.println("----------------------------------------------------------");
            System.out.println("Book ID    \t: " + super.bookID);
            System.out.println("Book name  \t: " + super.bookName);
            System.out.println("Author(s)  \t: " + author);
            System.out.println("Year       \t  " + year);
            System.out.println("----------------------------------------------------------\n");
        }
    }
}

此类创建一个Arraylist。

import java.util.ArrayList;

public class BookRecordSystem {
    public static void main(String[] args) {
        // TESTING Code below: for checking class data member
        System.out.println("SYSTEM START: Total number of books = " + Book.totalNoOfBook);
        // creating four default library books in a ArrayList here
        ArrayList<Book> bookList = new ArrayList<Book>(4);
        bookList.add(new LibraryBook("Cocoa Design Patterns",
                "Erik Buck & Donald Yacktman", 2009));
        bookList.add(new LibraryBook("Lord of the Files", "William Golding", 2013));
        bookList.add(new LibraryBook("Animal Farm", "George Orwell", 1996));
        bookList.add(new Book("A Book Life"));

        for (int i = 0; i < bookList.size(); i++) {
            Object obj = bookList.get(i);
            if (obj instanceof LibraryBook) {
                LibraryBook librarybook = (LibraryBook) obj;
                librarybook.printAvailableBookInfo();
            } else {
                Book bk = (Book) obj;
                bk.printAvailableBookInfo();

            }
        }

        System.out.println("SYSTEM END: Total number of books = " + Book.totalNoOfBook);
        System.out.println("End of program.");
        BookIO.writeLBFile("Sample", bookList); //pass to BookIO and write Object to the file

    }
}

将数据写入下面的class.file文件。 我试着写出图书馆的数据。但是,当我尝试运行程序时。我有一个错误“无法找到符号oos.writeObject(”作者:+ bList.get(i).author“); 我知道作者只存在于LibraryBook类中。我怎样才能打印子类数据? 是否使用类型转换来做到这一点?

import java.io.*;
import java.util.*;

public class BookIO implements Serializable {
    public static boolean writeLBFile(String oFileStr, ArrayList<Book> bList) {
        System.out.println("START of writeLBFile");
        if (bList == null) {
            return false;
        }

        try {
            File outFile = new File(oFileStr);
            FileOutputStream outFileStream = new FileOutputStream(outFile);
            ObjectOutputStream outObjectStream =
                    new ObjectOutputStream(outFileStream);


/*  for(int i = 0; i < bList.size() ; i++)
        if
        {

            oos.writeObject("The ID   :"+bList.get(i).bookID);
            oos.writeObject("The NAME  :"+bList.get(i).bookName);
            oos.writeObject("The NAME  :"+bList.get(i).author);

        }
        oos.close();
        outFileStream.close();
      }
}*/

            outObjectStream.close();
            outFileStream.close();
        } catch (FileNotFoundException ex) {
            System.out.println("ERROR - FileNotFoundException. Write Book Failure.");
            return false;
        } catch (IOException ex) {
            System.out.println("ERROR - IOException. Write Book Failure.");
            return false;
        }
        System.out.println("END of writeLBFile");
        return true;
    }
}

我期望在textfile中输出:

//Here is the output I expect in textfile
----------------------------------------------------------
                 LibraryBook                            
----------------------------------------------------------
Book ID:  :0
Book name :Coco Design Patterns
Author(s) :Erik Buck & Donald Yacktman
----------------------------------------------------------

----------------------------------------------------------
                 LibraryBook                            
----------------------------------------------------------
Book ID:  :1
Book name :Lord of the Files
Author(s) :William Colding
----------------------------------------------------------

----------------------------------------------------------
                 LibraryBook                            
----------------------------------------------------------
Book ID:  :2
Book name :Animal Farm
Author(s) :George Orwell
Year      :1996
----------------------------------------------------------

----------------------------------------------------------
                  Book                           
----------------------------------------------------------
Book ID:  :3
Book name :A Book Life
----------------------------------------------------------

2 个答案:

答案 0 :(得分:0)

对于大于1.7的java版本,请使用printwriter

try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(location, true))))   {
   out.println(text);
}catch (IOException e) {
   System.out.println(e);
}

在你的例子中

try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(location, true))))   {
     for(Book b:list)
     {
         out.println(".........................................");
         out.println("            LibraryBook");
         out.println(".........................................");
         //add book details
     }
    }catch (IOException e) {
       System.out.println(e);
    }

答案 1 :(得分:0)

实际上你没有在输出文件中写任何东西,试试这个:

try {
        File outFile = new File(oFileStr);
        FileOutputStream outFileStream = new FileOutputStream(outFile);
        ObjectOutputStream outObjectStream =
                new ObjectOutputStream(outFileStream);


Iterator<Book> it=bList.iterator();
while (it.hasNext()) {
    outObjectStream.writeObject((Book)it.next().printAvailableBookInfo());
}

        outObjectStream.close();
        outFileStream.close();
    } catch (FileNotFoundException ex) {
        System.out.println("ERROR - FileNotFoundException. Write Book Failure.");
        return false;
    } catch (IOException ex) {
        System.out.println("ERROR - IOException. Write Book Failure.");
        return false;
    }