首页 > 解决方案 > 如果该行不遵循特定模式,在读取文件时是否有指定消息的功能

问题描述

我正在制作一个名为 Book 的类,它代表具有标题、作者和年份的书籍,当他们获得奖项时。

我有一个 getList 方法,它应该从 csv 文件中读取数据,如果一行不遵循模式标题、作者、年份,那么应该将一条消息写入标准错误流。我无法确定如何指定错误消息。

我可以使用 BufferedReader 读取文件

但是,当验证所有 3 个值(标题、作者、年份)时,我不知道从哪里开始。我想我需要 3 个变量来检查 csv 的其中一行是否缺少(年份、作者等)。我是缓冲阅读器的新手,不知道该怎么做。任何帮助表示赞赏

我已经在互联网上查看并没有找到我正在寻找的确切内容

  package books;

 import java.io.BufferedReader;
 import java.io.FileReader;
 import java.io.IOException;
 import java.util.List;

 public class Book implements Comparable<Book> {
private String title;
private String author;
private int year;

/**
 * @param title
 * @param author
 * @param year
 */
public Book(String title, String author, int year) {
    this.title = title;
    this.author = author;
    this.year = year;
}

public String getTitle() {
    return title;
}

public String getAuthor() {
    return author;
}

public int getYear() {
    return year;
}

@Override
public String toString() {
    return title + " by " + author + " (" + year + ")";

}

public static List<Book> getList(String file) {

    try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
        while (reader.ready()) {

            System.out.println(reader.readLine());
        }
        System.out.println();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

@Override
public int compareTo(Book o) {
    // TODO Auto-generated method stub
    return 0;
}

  }

测试应用

 package books;


 public class BookApp {

public static void main(String[] args)  {
    Book book = new Book ("Harry Potter and the Sorcerer's Stone", "J. K. Rowling", 1997);
    System.out.println(book.toString());

    System.out.println();
    book.getList("src/books/books.csv");
}
}

标签: javafilereaderbuffered

解决方案


嘿,您可以使用以下代码来解析和验证书籍:


public static List<Book> getList(String file) {
// create a new list of books
    List<Book> books = new ArrayList<>();
    try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
        while (reader.ready()) {
            // read line of reader
            String bookLine = reader.readLine();
            Book book = toBook(bookLine);
            if (book != null) { //only add the book if it is non empty
                books.add(book);
            }
        }
        System.out.println();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return books;
}

private static Book toBook(String bookLine) {
    String[] bookParts = bookLine.split(",");
    if (bookParts.length < 3) { //validate if all three parts are present
        System.err.println(String.format("The line %s did not contain all parts", bookLine));
        return null;
    }
    if (bookParts[0].trim().isEmpty()) { // validate the book has a title
        System.err.println(String.format("The line %s did contain an empty title", bookLine));
        return null;
    }

    if (bookParts[1].trim().isEmpty()) { // validate the book has an author
        System.err.println(String.format("The line %s did contain an empty author", bookLine));
        return null;
    }
    if (!bookParts[2].trim().matches("\\d{4}")) { // checks if the year (3rd part is a number. Where \\d is for numeric and {4} means 4 digits)
        System.err.println(String.format("The line %s did contain a non-numeric value as year", bookLine));
        return null;
    }
    return new Book(bookParts[0], bookParts[1], Integer.parseInt(bookParts[2]));
}


推荐阅读