我已经编写了以下方法来序列化对象并将其写入.csv文件:它运行良好。
public static void serializeAsCSV(String path, Book book) throws IOException {
Path filePath = Paths.get(path); //create a new path object, passing the path
byte[] strToBytes = book.prettyPrintCSV().getBytes();//converts the String to bytes
Files.write(filePath, strToBytes); //writes the bytes to the file
我想我没有完全理解它,因为我在编写将.csv文件反序列化为对象的方法时遇到了问题。
这就是我目前拥有的:
public static void deserializeFromCSV(String path, Book book) throws IOException {
List<List<String>> records = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader("books.csv"))) {
String line;
while ((line = br.readLine()) != null) {
String[] values = line.split(",");
records.add(Arrays.asList(values));
records.add(Arrays.asList(values));
}
调用序列化/反序列化的主要方法:
public static void main(String[] args) throws IOException {
Book book = new Book("Donald", "Male", "Brown"); //create a new instance of Book
System.out.println(book.prettyPrintCSV()); //output the String values of new Book instance, moves to new line
Book.serializeAsCSV("books.csv", book); //calls the serializeAsCSV method, passing the path and the book object
Book.deserializeFromCSV("books.csv", book); //calls the deserializeFromCSV method, passing the path
}
请忽略那些与书籍无关的属性。我把班级从";婴儿"至";书";我需要重构。
您必须为每一行创建新的图书实例:
while ((line = br.readLine()) != null) {
String[] values = line.split(",");
records.add(new Book(values[0], values[1],values[2]));
}
此外,您应该在末尾返回您的列表,以及为什么desirialize方法有参数book
?同样,列表没有意义,你只序列化了一本书