首页 > 解决方案 > 如何将 Arraylist 保存并打印到文件中?

问题描述

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

class Book implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private String author;

public String getAuthor() {
    return author;
}

public Book(String name, String author) {
    this.name = name;
    this.author = author;
}

public void disPlay() {
    System.out.print("Book name : " + name);
    System.out.println("\tAuthor name : " + author);
}
}

public class Print {
public static void main(String[] args) throws Exception {
    writeList();
    List<Book> list = readList();
    for (Book obj : list)
        System.out.println(obj);
}

public static List<Book> readList() throws Exception {
    ObjectInputStream in = new ObjectInputStream(new FileInputStream("object.dat"));
    @SuppressWarnings("unchecked")
    List<Book> readObject = (List<Book>) in.readObject();
    in.close();
    return readList();
}

public static void writeList() throws Exception {
    List<Book> list = new ArrayList<>();
    ObjectOutputStream out = null;
    try (Scanner scan = new Scanner(System.in)) {
        System.out.print("Enter the book, author name : ");
        String name = scan.next();
        String author = scan.next();
        list.add(new Book(name, author));
        System.out.print("If you want to save to the list -1, if you don't want, enter 1 : ");
        int choice = scan.nextInt();
        out = new ObjectOutputStream(new FileOutputStream("object.dat"));
        out.flush();
        out.close();
        System.out.print("Save the list to a file");
    }
}
}

我尝试获取存储在文件(object.dat)中的ArrayList对象,将Book对象保存在ArrayList中,然后在程序结束前将Book对象所在的ArrayList保存在文件中。

我想要的结果是,[程序首次运行时的结果]

There are no saved values

Enter the book, author name : Harrypotter jkrowling
If you want to save to the list -1, if you don't want, enter 1 : -1
Save the list to a file

并且,[第二次及以后的结果]

---Outputs the value stored in the file name---
Book name : Harrypotter
Author name : jkrowling

Enter the book, author name : Twilight StephenieMeyer
If you want to save to the list -1, if you don't want, enter 1 : 1
Save the list to a file

我想这样打印出来,但我该怎么办?

标签: java

解决方案


这是在java中写入文件的一般方法。

import java.io.FileWriter;   // Import the FileWriter class
try {
      FileWriter myWriter = new FileWriter("filename.txt");
      myWriter.write("Write into file here! ");
      myWriter.close();
      System.out.println("Successfully wrote to the file.");
    } catch (IOException e) {
      System.out.println("An error occurred.");
      e.printStackTrace();
    }

推荐阅读