我认为文件应该被定义为一个字段(除了filename
之外),并建议从用户的主目录中读取它:file
private File file = new File(System.getProperty("user.home"), filename);
然后,当您定义您的
List
时,可以使用菱形运算符
<>
。您可以使用
try-with-resources
来
close
您的
Scanner
。您想要按行读取。然后,您可以
split
您的
line
。接下来,测试您的第一列是否与名称匹配。如果是,则迭代其他列并将它们解析为
int
。类似于:
public List<Integer> loadDataFor(String name) throws IOException {
List<Integer> data = new ArrayList<>();
try (Scanner s = new Scanner(file)) {
while (s.hasNextLine()) {
String[] row = s.nextLine().split("\\s+");
if (row[0].equalsIgnoreCase(name)) {
for (int i = 1; i < row.length; i++) {
data.add(Integer.parseInt(row[i]));
}
}
}
}
return data;
}
将文件扫描一次并将名称和字段存储为Map<String,List<Integer>>
可能更有效率,如下所示:
public static Map<String, List<Integer>> readFile(String filename) {
Map<String, List<Integer>> map = new HashMap<>();
File file = new File(System.getProperty("user.home"), filename);
try (Scanner s = new Scanner(file)) {
while (s.hasNextLine()) {
String[] row = s.nextLine().split("\\s+");
List<Integer> al = new ArrayList<>();
for (int i = 1; i < row.length; i++) {
al.add(Integer.parseInt(row[i]));
}
map.put(row[0], al);
}
} catch (Exception e) {
e.printStackTrace();
}
return map;
}
然后将其存储为fileContents
,如下所示:
private Map<String, List<Integer>> fileContents = readFile(filename)
然后使用fileContents
实现你的loadDataFor(String)
方法,例如:
public List<Integer> loadDataFor(String name) throws IOException {
return fileContents.get(name);
}
如果您的使用模式涉及读取许多名称的
File
,那么第二个选项可能会更快。