我创建了一个名为ReadFile的类,用于将多个文件中的数据(元素的数量和数量)加载到2个arraylist中,以存储元素数量的两个数量。如何在不重复读取文件代码的情况下获得4个元素和以下数字?
样本输入文件
4
1 10 9 8
public class ReadFile {
public List <Integer> getNumbers(){
List<Integer> numbers = new ArrayList<>();
File folder = new File("/Users/Mary/NetBeansProjects/Sample/src/program/pkg4/Input");
for (File file : folder.listFiles()) {
try{
FileReader fileReader = new FileReader(file);
BufferedReader reader = new BufferedReader(fileReader);
String numberOfElement = reader.readLine();
String line = reader.readLine();
for (String s : line.split("\\s+")) {
numbers.add(Integer.parseInt(s));
}
reader.close();
}catch(IOException e){
System.out.println("ERROR: There was a problem reading the file.\n" + e.getMessage());
}
}
return numbers;
}
public List <Integer> getElements(){
List<Integer> elements = new ArrayList<>();
File folder = new File("/Users/Mary/NetBeansProjects/Sample/src/program/pkg4/Input");
for (File file : folder.listFiles()) {
try{
FileReader fileReader = new FileReader(file);
BufferedReader reader = new BufferedReader(fileReader);
String numberOfElement = reader.readLine();
elements.add(Integer.parseInt(numberOfElement));
reader.close();
}catch(IOException e){
System.out.println("ERROR: There was a problem reading the file.\n" + e.getMessage());
}
}
return elements;
}
}
答案 0 :(得分:0)
您可以按照@jonathan Heindl的建议进行操作(将整个文件读入字符串),或者至少可以将创建读取器的方法移出两种方法之外:
public void parseFile()) {
File folder = ...;
for (File file : folder.listFiles()) {
try {
// create reader for this file
...
int number = getNumber(reader);
List<Integer> = getElements(reader, number);
} catch( ... ) {
...
}
}
}
您甚至可能希望将元素列表放在以文件名作为关键字的地图中。从注释中还不清楚单个文件中是否有多个列表,因此您可能需要采取其他措施来处理这种情况