2013-03-23 79 views
0

我想打开保存在JAR中的.txt文件,并将其内容显示在JTextArea中。以下是我尝试使用的代码;从JAR打开文本文件而不提取它 - 请帮助

URL urlToDictionary = this.getClass().getResource("eula/" + "eula.txt"); 
     try { 
     InputStream stream = urlToDictionary.openStream(); 
     gettysburgTextStrBlder = stream; 
     System.out.println(stream); 
    } catch (IOException e1) { 
     // TODO Auto-generated catch block 
     e1.printStackTrace(); 
    } 

我知道我是在正确的文件的位置,因为我已经改变了周围的.getResource路径,看到零点例外,我没有与当前文件的路径。

的System.out的打印在运行时执行以下操作:

[email protected] 

我也曾尝试;

gettysburgTextStrBlder = String.valueOf(stream); 

但我得到的结果是一样的。

我想我已经快到了,但我不确定如何获取.txt文件的实际内容,而不仅仅是缓冲流。

谢谢。

安迪

回答

3

你必须使用BufferedReader

URL urlToDictionary = this.getClass().getResource("eula/" + "eula.txt"); 
    try { 
    InputStream stream = urlToDictionary.openStream(); 
    BufferedReader br = new BufferedReader(new InputStreamReader(stream)); 
    String line = null; 
    StringBuffer lineContent = new StringBuffer(); 
    while((line = br.readLine()) != null){ 
     lineContent.append(line).append("\n"); 
    } 
    br.close(). 
    System.out.println(lineContent.toString()); 
} catch (IOException e1) { 
    // TODO Auto-generated catch block 
    e1.printStackTrace(); 
} 
+0

由于读取文本区域的InputStream和显示的内容,我必须失去了别的东西,该行lineConent.add(行) ; eclipse是说“方法add(String)是未定义的类型StringBuffer” – andy 2013-03-23 13:22:51

+0

我的错误。它是'append'而不是'add'。更正了我的答案。 – 2013-03-23 13:41:46

+0

谢谢,完美的工作。有没有一种方法可以从文本文件中检测到回车符? JTextArea将文本全部显示为一行。 – andy 2013-03-23 13:50:16