我想读取一个包含String和与该字符串相关的几个整数的文本文件。
这是我必须编写程序的类:
public List<Integer> Data(String name) throws IOException {
return null;
}
我必须阅读.txt文件,并在其中找到该文件中的名称及其数据。并将其保存在ArrayList
中。
我的问题是,当ArrayList<Integer>
中有String
时,如何将其保存在List
。
这就是我想我会做的事情:
Scanner s = new Scanner(new File(filename));
ArrayList<Integer> data = new ArrayList<Integer>();
while (s.hasNextLine()) {
data.add(s.nextInt());
}
s.close();
答案 0 :(得分:3)
我会将文件定义为字段(除了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);
然后将其存储为loadDataFor(String)
fileContents
然后使用public List<Integer> loadDataFor(String name) throws IOException {
return fileContents.get(name);
}
File
方法
class AController < ApplicationController
before_action :set_title
private
def set_title
@title = 'Email Subscription'
end
end
如果您的使用模式为许多名称读取module ApplicationHelper
def title_suffix
" - #{@title}" unless @title.nil?
end
end
,那么第二个可能会快得多。
答案 1 :(得分:0)
如果你想使用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