[英]Getting integer data from txt file in Java
我想读取一个文本文件,其中包含String和与该字符串相关的几个整数。
这是我必须编写程序的类:
public List<Integer> Data(String name) throws IOException {
return null;
}
我必须读取.txt文件并在其中找到该文件中的名称及其数据。 并将其保存在ArrayList
。
我的问题是当我在List
有String
时,如何将它保存在ArrayList<Integer>
中。
这就是我想我会做的事情:
Scanner s = new Scanner(new File(filename));
ArrayList<Integer> data = new ArrayList<Integer>();
while (s.hasNextLine()) {
data.add(s.nextInt());
}
s.close();
我将文件定义为一个字段(除了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
,那么第二个可能会快得多。
如果你想使用java8,你可以使用这样的东西。
Input.txt(必须在类路径中):
text1;4711;4712
text2;42;43
代码:
public class Main {
public static void main(String[] args) throws IOException, URISyntaxException {
// find file in classpath
Path path = Paths.get(ClassLoader.getSystemResource("input.txt").toURI());
// find the matching line
findLineData(path, "text2")
// print each value as line to the console output
.forEach(System.out::println);
}
/** searches for a line in a textfile and returns the line's data */
private static IntStream findLineData(Path path, String searchText) throws IOException {
// securely open the file in a "try" block and read all lines as stream
try (Stream<String> lines = Files.lines(path)) {
return lines
// split each line by a separator pattern (semicolon in this example)
.map(line -> line.split(";"))
// find the line, whiches first element matches the search criteria
.filter(data -> searchText.equals(data[0]))
// foreach match make a stream of all of the items
.map(data -> Arrays.stream(data)
// skip the first one (the string name)
.skip(1)
// parse all values from String to int
.mapToInt(Integer::parseInt))
// return one match
.findAny().get();
}
}
}
输出:
42
43
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.