csv 反转此序列化的最佳方式

ctehm74n  于 2022-12-06  发布在  其他
关注(0)|答案(1)|浏览(133)

我编写了以下方法来序列化对象并将其写入.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
    }

请忽略那些与书籍无关的属性。我将类从“Baby”改为“Book”,我需要重构。

fkvaft9z

fkvaft9z1#

您必须为每一行创建新的帐簿示例:

while ((line = br.readLine()) != null) {
    String[] values = line.split(",");
    records.add(new Book(values[0], values[1],values[2]));
}

另外,你应该在最后返回你的列表,为什么你有desirialize方法的参数book?同样,列表没有意义,你只序列化一本书

相关问题