我需要在文本文件中用逗号分隔名称和数字,并将它们添加到单独的 ArrayList 中。我有一种将每个新行添加到单个 ArrayList 中的方法。这是代码。
File file = new File(mPath);
if (file.exists()){
StringBuilder builder = new StringBuilder();
try{
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
String line;
while( (line = bufferedReader.readLine()) != null){
allNames.add(line);
}
bufferedReader.close();
}
catch(IOException e){
e.printStackTrace();
}
return allNames;
}
我是 Java 新手,所以请不要歧视!!
最佳答案
你应该可以在这里使用String#split
:
while( (line = bufferedReader.readLine()) != null) {
allNames.add(line.split(", ")[0]);
}
这假设您的文本文件具有以下形式的数据:
Hector, 1104
Johnny, 4302
Chano, 1123
在这种情况下,您只想捕获每行第一个逗号之前的所有内容。
编辑:
如果要捕获数字,请使用:
Integer.parseInt(line.split(",\\s+")[1])
关于java - 如何使用逗号和换行符解析 .text 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55234242/