[英]How do I read multiple tokens between characters in java?
I am doing a project where I need to read multiple lines that contains user data from a txt file.我正在做一个项目,我需要从 txt 文件中读取包含用户数据的多行。 This data will create a profile.
此数据将创建一个配置文件。
For example:例如:
name,lastname,email,hobbies1;hobbies2...hobbiesN,activity1;activity2...activityN
name2,lastname2,email.... and so on
I don't know how many hobbies or activities are there so I have to set them into an array.我不知道有多少爱好或活动,所以我必须将它们设置成一个数组。 All of variables are on one line.
所有变量都在一行上。 I tried using delimiter and split, but when I move onto the next line I get inputMismatchException.
我尝试使用分隔符和拆分,但是当我进入下一行时,我得到了 inputMismatchException。
Simplest way is to change the format.最简单的方法是改变格式。
Instead of separating every field with ,
try using ;
不要用 分隔每个字段
,
而是尝试使用;
for separating different types of attributes and ,
for elements of arrays.用于分隔不同类型的属性和
,
用于 arrays 的元素。 The end result will be something like:最终结果将类似于:
name; lastname; email; hobbies1, hobbies2, ..., hobbiesN; activity1, activity2, ..., activityN
First you split the String
using ;
首先,您使用
;
拆分String
as delimiter, then for those fields that allows for arrays you divide the array in its elements by splitting that sub String
with ,
as delimiter.作为分隔符,然后对于那些允许 arrays 的字段,您可以通过将子
String
拆分为,
作为分隔符来划分数组的元素。
Read lines, then split on comma, and split on semi-colon where needed.读取行,然后以逗号分隔,并在需要时以分号分隔。
Don't use Scanner
for line-reading a file.不要使用
Scanner
对文件进行行读取。
try (BufferedReader in = Files.newBufferedReader(Paths.get("test.txt"))) {
for (String line; (line = in.readLine()) != null; ) {
String[] fields = line.split(",");
String name = (fields.length >= 1 ? fields[0] : "");
String lastname = (fields.length >= 2 ? fields[1] : "");
String email = (fields.length >= 3 ? fields[2] : "");
String[] hobbies = (fields.length >= 4 ? fields[3].split(";") : new String[0]);
String[] activities = (fields.length >= 5 ? fields[4].split(";") : new String[0]);
System.out.println("name=" + name +
", lastname=" + lastname +
", email=" + email +
", hobbies=" + Arrays.toString(hobbies) +
", activities=" + Arrays.toString(activities));
}
}
test.txt测试.txt
name,lastname,email,hobbies1;hobbies2...hobbiesN,activity1;activity2...activityN
name2,lastname2,email
Output Output
name=name, lastname=lastname, email=email, hobbies=[hobbies1, hobbies2...hobbiesN], activities=[activity1, activity2...activityN]
name=name2, lastname=lastname2, email=email, hobbies=[], activities=[]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.