java - 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);
}
}
}
解决方案
一个简单的解决方案是为 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));
}
}
推荐阅读
- vue.js - Companies House(UK) get request, axios
- tensorflow - 如何使用在另一个张量中指定的索引在 tensorflow 中创建一个中间范围仅设置为 True 的布尔掩码
- spring-boot - @RequestHeader 行为不符合预期;无需用户代理即可工作
- c - 未初始化的指向指针的指针的临时值
- cassandra - 我们可以使用集群名称而不是 IP 地址连接到 Cassandra 吗?
- java - POJO 中 JSONObject 字段的 SpringBoot 和 MongoDB 保存问题
- sql-server - 生产服务器上的编码问题
- c# - 枚举转换整数和数字
- java - 错误 decrjavax.crypto.BadPaddingException:给定最终块未正确填充。如果在解密期间使用了错误的密钥,则可能会出现此类问题
- firebase-realtime-database - Firebase 路径无效:Firebase 路径不得包含“.”、“#”、“$”、“[”或“]”