首页 > 解决方案 > Java,从文本文件中读取包含不同的分隔符

问题描述

我的文本文件包含不同的分隔符,在每个分隔符之后(例如:#、#*、#@、#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);
        }
    }
}

标签: javafile

解决方案


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

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));
    }
}

推荐阅读