2016-05-10 59 views
0

我需要读取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:尚未支持。

+0

我可能需要添加,文本文件中的每一行有5个元素用“/”分隔。我需要第一个元素,它是一个字符串,第二个和最后一个 - 它们是数字。 – gheithen

+0

你是什么意思,但这似乎并没有解决我的问题?抛出异常?意外的输出? – Frank

+0

我在popSet.add部分收到错误消息。它表示预期 – gheithen

回答

0

您的代码存在的问题是您没有存储您从缓冲区读取的内容(并因此从缓冲区读取两次)。您需要为您分配一个变量读什么检查如下空:

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

此外,我将关闭的BufferedReader在finally块以避免资源泄漏。

+0

谢谢,我仍然在这里得到了标识符问题,我尝试将数组添加到treeSet – gheithen

+0

,正如其他人所建议的那样,这可能是由于编译问题(由于Integer.parseInt中的额外点()。尝试解决这个问题。我已经更新了编译错误的修复代码。 – Vijay

+0

我也更新了它。现在我收到这条消息:线程“main”中的异常java.lang.UnsupportedOperationException:不支持 – gheithen

2

您在parseIntInteger.parseInt.(array[4])));之后有额外的时间。

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

+0

删除它,仍然出错 – gheithen

+2

你已经做好了在另一个'parseInt'上也是一样的错误。来吧,注意一下。 – Kayaman

+0

我没有删除期限! – gheithen

0

我试图用你的代码重现错误,但它没有发生。你的代码是可以的。

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

但是TreeSet实现了add方法。