从txt读取并添加到treeset

时间:2016-05-10 12:22:09

标签: java bufferedreader 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:尚不支持。

3 个答案:

答案 0 :(得分:2)

parseInt Integer.parseInt.(array[4])));之后您有一段额外的时间。

编写代码时要小心。语法错误不会“很好地”显示,即错误消息在大多数情况下不是很有用。它确实显示了错误的大致位置。

答案 1 :(得分:0)

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

    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以避免资源泄漏。

答案 2 :(得分:0)

我尝试使用您的代码重现错误,但它没有发生。你的代码还可以。

UnsupportedOperationException是尝试在集合中添加元素时可能发生的异常。

但是TreeSet实现了add方法。

相关问题