从txt读取并添加到树集

yhqotfr8  于 2021-07-03  发布在  Java
关注(0)|答案(3)|浏览(355)

我需要读取一个txt文件并将数据存储到树集。

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);
}

}

我曾尝试将缓冲读取器读取的内容转换为数组,然后将其添加到我的树集中,但出现了错误:线程“main”java.lang.unsupportedoperationexception中的异常:尚不支持。

plupiseo

plupiseo1#

你有一个额外的时期后 parseIntInteger.parseInt.(array[4]))); .
写代码时要小心。语法错误不会“很好地”显示出来,也就是说,在大多数情况下,错误消息不是很有用。不过,它确实向您显示了错误的大致位置。

bfrts1fy

bfrts1fy2#

代码的问题是没有存储从缓冲区读取的内容(因此从缓冲区读取了两次)。您需要指定在变量中读取的内容以检查空值,如下所示:

private void readFile(String fileName) throws IOException {

        try {
            br = new BufferedReader(new FileReader(fileName));
            String line = null;
            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();
        } finally {
            br.close();
        }
    }

我还将关闭finally块中的bufferedreader以避免资源泄漏。

oaxa6hgo

oaxa6hgo3#

我试图用你的代码重现这个错误,但没有发生。你的代码没问题。 UnsupportedOperationException 是在尝试向集合中添加元素时可能发生的异常。
但是 TreeSet 实现add方法。

相关问题