有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java用JAR打开文本文件而不提取帮助

我正试图打开一个新的窗口。保存在JAR中的txt文件,并在JTextArea中显示其内容。下面是我试图使用的代码

 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 path出现了空点异常,我对当前文件路径没有任何异常

系统。out在运行时打印以下内容:

java.io.BufferedInputStream@3af42ad0

我也尝试过

gettysburgTextStrBlder = String.valueOf(stream);

但我得到的结果是一样的

我想我就快到了,但我不确定如何获得这本书的实际内容。txt文件,而不仅仅是缓冲流

谢谢

安迪


共 (1) 个答案

  1. # 1 楼答案

    您必须从inputstream读取内容,并使用^{}显示在文本区域中

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