基本上你希望文件的每一列都是一个数组列表。您需要执行以下操作:
- 创建一个最初为空的数组列表列表
- 以阅读模式打开文件
- 逐行读取,直到不为空
- 对于每一行,用逗号分隔(我假设逗号是分隔符)
- 遍历以逗号分隔的块
- 如果找到空值,则跳过它
- 检查
List<String>的列表是否在第i个位置包含List<String>,如果是,则检索该List<String>并将块[ith]添加到它并将其添加回主列表(在第i个位置替换旧的List<String>)
- 如果
main 列表在第i 个位置不包含List<String>,则创建一个新的List<String>,将块[i] 添加到其中,然后将其添加到主列表。
将上述内容应用于您的输入
循环通过a,b,c,d for List<String> 被添加到List<List<String>> 结构中,每个结构分别包含a,b,c and d。
循环通过第二行hello, hi and hey 前三个List 从List<List<String>> 结构中检索并再次更新和存储。
假设您的第三行包含1,2,3,4,5(比上述两行多一个)。循环将从 List<List<String>> 中找到 4 List<String> 并分别用 1、2、3 和 4 更新它们,但是 5 呢? List<List<String>> 在 5 中不包含 List<String>,因为其他行只有 4 个块,所以创建一个新的 List<String> 并添加 5,然后将其添加到 List<List<String>>。
这是一个示例代码,它实际上执行了我上面描述的操作。我假设你想要 ArrayList 行中的东西。
//list that stores list of strings
List<List<String>> list = new ArrayList<List<String>>();
try {
//open file in read mode, change the file location
BufferedReader br = new BufferedReader(new FileReader("C:\\test_java\\content.txt"));
String line = "";
//read each line as long as line != null which indicates end of file
while((line=br.readLine()) != null) {
//split the line into chunks using comma as seperator
String[] chunks = line.split(",");
//loop through chunks of vlaues
for(int i = 0; i < chunks.length; i++) {
//if chunks[i] is not empty
if(chunks[i].trim().length() > 0) {
//there is a List<String> in list.get(i) so get the List<String> update it and put it back
if(list.size() > i) {
List<String> temp = list.get(i);
temp.add(chunks[i]);
list.remove(i);
list.add(i, temp);
} else {
//there was no list in list.get(i) so create a new List<String> and add it there
List<String> temp = new ArrayList<String>();
temp.add(chunks[i]);
list.add(temp);
}
}
}
}
//close read stream
br.close();
} catch(Exception e){
e.printStackTrace(System.out);
}
//print the list
for(List<String> l: list) {
System.out.println(l);
}
您提供的输入文件的输出
[[a, hello, bye, z], [b, hi, ciao, y], [c, hey, adios, x], [d, w]]
如果您想获得问题中所示的精确输出,那么您可以遍历List<List<String>> 并从每个List<String> 的元素中创建一个单个字符串,并用双引号对其进行后缀。见下文,我使用 Java 8 的迭代器来迭代 List<String> 并创建 StringBuilder obj。
String[] s = new String[list.size()];
int i = 0;
for(List<String> l: list) {
StringBuilder b = new StringBuilder("\"");
//java 8 loop through list and for each element add it to StrinbBuilder obj
l.stream().forEach(e -> b.append(e + " "));
b.append("\"");
s[i++] = b.toString();
}
System.out.println(Arrays.toString(s));
上面会给你
["a hello bye z ", "b hi ciao y ", "c hey adios x ", "d w "]