【发布时间】:2016-10-13 00:10:43
【问题描述】:
我有以下 txt 文件,我需要用令牌拆分并保存到一个对象:
1,哈利波特,4,3,11,14,20
2,矩阵,3,1,8,12
3,蝙蝠侠,3,39,9,42
结构是:id、name、length、movieIds
其中长度是指有多少个movieId。
不确定如何分别拆分movieIds 或为对象设置多个值,因为它们会相互覆盖。
Scanner inputFile = new Scanner(playlistLibrary);
String str;
String[] tokens;
for (int i = 1; i < playlist.length; i ++) {
playlist[i] = new Playlist_17967352();
if (inputFile.hasNext()) {
str = inputFile.nextLine();
tokens = str.split(",");
for (int a = 0; a < tokens.length; a ++) {
playlist[i].setId(tokens[0]);
playlist[i].setName(tokens[1]);
playlist[i].setLength(tokens[2]);
if (tokens.length > 3) {
int length = Integer.parseInt(playlist[i].getLength());
String movieIds;
for (int b = 0, c = 3 ; b < length; b++, c++) {
movieIds = tokens[c];
playlist[i].setMovies(movieIds);
}
}
} // end for tokens.length
System.out.println(playlist[i].getMovies());
代码输出:
20
12
42
我需要的是:
3,11,14,20
1,8,12
39,9,42
【问题讨论】:
-
是否可以更新文件格式? 1,哈利波特,4,"3,11,14,20" 2,矩阵,3,"1,8,12" 3,蝙蝠侠,3,"39,9,42"
-
看起来像 CSV (Comma-Separated Values) 数据,所以使用 CSV 解析器,例如Apache Commons CSV.
-
@Andreas 是的,但他的 CSV 格式不会转义movieIds,因此除非他添加引号,否则它将无法正常工作
-
setMovies()的签名是什么? -
@42shadow42 在 Java 结构中将
movieIds存储为逗号分隔的字符串不是正确的答案(在我看来)。它应该是List<Integer>或int[]。因此,这些值是 CSV 文本中真正独立的值。
标签: java arrays class token delimiter