Jav*_*ner 6 java file-io arraylist
我想读取一个文本文件,其中包含String和与该字符串相关的几个整数.
这是我必须编写程序的类:
public List<Integer> Data(String name) throws IOException {
return null;
}
Run Code Online (Sandbox Code Playgroud)
我必须读取.txt文件并在其中找到该文件中的名称及其数据.并保存在一个ArrayList
.
我的问题是我怎么保存它的ArrayList<Integer>
时候我已经String
在S List
.
这就是我想我会做的事情:
Scanner s = new Scanner(new File(filename));
ArrayList<Integer> data = new ArrayList<Integer>();
while (s.hasNextLine()) {
data.add(s.nextInt());
}
s.close();
Run Code Online (Sandbox Code Playgroud)
我会将文件定义为一个字段(除了 之外filename
,我建议从用户的主文件夹中读取它)file
private File file = new File(System.getProperty("user.home"), filename);
Run Code Online (Sandbox Code Playgroud)
然后,您可以<>
在定义List
. 您可以将 a 用于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;
}
Run Code Online (Sandbox Code Playgroud)
扫描一次文件并将名称和字段存储为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;
}
Run Code Online (Sandbox Code Playgroud)
然后将其存储fileContents
为
private Map<String, List<Integer>> fileContents = readFile(filename);
Run Code Online (Sandbox Code Playgroud)
然后loadDataFor(String)
用fileContents
类似的方法实现你的方法
public List<Integer> loadDataFor(String name) throws IOException {
return fileContents.get(name);
}
Run Code Online (Sandbox Code Playgroud)
如果您的使用模式读取File
多个名称,那么第二个可能会快得多。