java - 如何将 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中写入文件的一般方法。
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();
}
推荐阅读
- node.js - 此 set-cookie 被阻止,因为它的域属性对于当前主机 url 无效
- c# - 用户输入无法保存到数据库
- mysql - 使用 date(createdAt) 和不使用 createdAt 的区别
- java - 如何解决此警告 将此 lambda 替换为 forEach 中的方法引用
- php - Laravel apache公共索引未显示页面
- triggers - GTM Click ID 触发整个对象
- mendix - 如何在 Mendix 中配置 Google OCR?
- css - 如何更正 CSS 文件中的 $ 标记?
- javascript - 如何将内联事件处理程序替换为幻灯片中的事件侦听器
- sql-server - 如何在 Visual Studio 中从 SQL 查询(.sql 文件)创建仪表板