Java,Read From文件包含不同的分隔符

时间:2018-06-04 13:26:10

标签: java file

我的文本文件包含不同的分隔符,在每个分隔符之后(例如:#,#*,#@,#o),有一个特定的值,我如何单独读取每个值并将所有值添加到单个对象?

文本文件示例:

#index 1
#* Book Review: Discover Linux
#@ Marjorie Richardson
#o -
#t 1998
#c Linux Journal

我尝试了什么:

public void ReadFile (String fileName) throws IOException {
    File file = new File(fileName);
    BufferedReader br = new BufferedReader(new FileReader(file));
    List<Book> books = new ArrayList<>();
    String fileRead = br.readLine();
    while (fileRead != null) {
        if (fileRead.startsWith("#")) {
            String index = fileRead;
            Book b = new Book();
            b.AddBook(index);
            books.add(b);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

一个简单的解决方案是在Book类中为相关的setter创建一个字符映射:

private static final Map<Character, BiConsumer<Book, String>> CODE_TO_SETTER =
    new HashMap<>();

static
{
    CODE_TO_SETTER.put('*', Book::setTitle);
    CODE_TO_SETTER.put('@', Book::setAuthor);
    // plus any others you want
}

然后,当你在线上迭代时,每次看到#index时都要创建一本新书,并在每本以哈希符号开头的行上调用当前书籍的setter:

Book book = null;
while (fileRead != null) {
    if (fileRead.startsWith("#index"))
    {
        if (book != null) // we're finished with the current book
        {
            books.add(book);
        }
        book = new Book();
    }
    else if (fileRead.startsWith("#"))
    {
        CODE_TO_SETTER.get(fileRead.charAt(1)).accept(book, fileRead.substring(3));
    }
}