[英]Is there a way to store data into an array from an input file where the name of the array is given in the file?
我想要一个具有以下格式的输入文件:ArrayName Value其中ArrayName是您要在其中存储值的数组的名称。输入的每一行都可以存储在新数组或现有数组中。 我遇到的问题是我不知道如何从文件中获取ArrayName并从中创建一个数组。 或者如果数组已经存在,我不确定如何将值存储到具有该名称的数组中。
我不确定为什么要从文件中命名数组,也许您可以对此进行解释。 但是与此同时,您可以做的一件事是:
1.以HashMap<String, int[]>
的形式声明一个数组的HashMap<String, int[]>
(即,如果您的数据是整数)。
2.从文件中读取数组的名称,并使用数组名称作为键将其元素存储在映射中。
完成后,您将如何知道对哪个阵列进行了处理? 我建议您使用Map<String, List<String>>
。
Map<String, List<String>> map = new HashMap<>();
然后,您可以使用Scanner
从文件中读取密钥 ,然后使用诸如try-with-resources
清理
try (Scanner s = new Scanner(new File(filePath))) {
Map<String, List<String>> map = new HashMap<>();
while (s.hasNextLine()) {
String line = s.nextLine();
String[] parts = line.split("\\s+");
String name = (parts.length > 1) ? parts[0] : "";
String value = (parts.length > 1) ? parts[1] : "";
List<String> al = map.get(name);
if (al == null) {
al = new ArrayList<>();
map.put(name, al);
}
al.add(value);
}
System.out.println(map); // <-- print the map.
} catch (Exception e) {
e.printStackTrace();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.