我需要读取txt文件并将我的数据存储到treeSet。从txt读取并添加到treeset
public class UrbanPopulationStatistics {
private Set<UrbanPopulation> popSet;
private File file;
private BufferedReader br;
public UrbanPopulationStatistics(String fileName) throws IOException {
this.popSet = new TreeSet<>();
readFile("population.txt");
}
private void readFile(String fileName) throws IOException {
try {
br = new BufferedReader(new FileReader(fileName));
String line;
while ((line=br.readLine()) != null) {
String[] array = line.split("/");
popSet.add(new UrbanPopulation(array[0], Integer.parseInt(array[1]), Integer.parseInt(array[4])));
}
} catch (IOException e) {
e.printStackTrace();
}
br.close();
}
@Override
public String toString() {
String s = popSet.toString().replaceAll(", ", "");
return "UrbanPopulationStatistics:\n" + s.substring(1, s.length() - 1) + "\n";
}
public static void main(String[] args) throws IOException {
UrbanPopulationStatistics stats = new UrbanPopulationStatistics("population.txt");
System.out.println(stats);
}
}
我曾试图把什么缓存读取器读取到一个数组,然后将其添加到我的TreeSet的,但我得到的错误:异常线程“main” java.lang.UnsupportedOperationException:尚未支持。
我可能需要添加,文本文件中的每一行有5个元素用“/”分隔。我需要第一个元素,它是一个字符串,第二个和最后一个 - 它们是数字。 – gheithen
你是什么意思,但这似乎并没有解决我的问题?抛出异常?意外的输出? – Frank
我在popSet.add部分收到错误消息。它表示预期 –
gheithen