java - Main.class.getResource() 和 jTextArea

标签 java swing file-io jtextarea getresource

当我从 jar 文件中读取文件并希望将其放入 jTextArea 中时,它会显示加密符号,而不是真实内容。

我在做什么:

public File loadReadme() {
    URL url = Main.class.getResource("/readme.txt");
    File file = null;

    try {
        JarURLConnection connection = (JarURLConnection) url
                .openConnection();
        file = new File(connection.getJarFileURL().toURI());

        if (file.exists()) {
            this.readme = file;
            System.out.println("all ok!");

        }
    } catch (Exception e) {
        System.out.println("not ok");
    }

    return file;
}

然后我读了文件:

public ArrayList<String> readFileToArray(File file) {
    ArrayList<String> array = new ArrayList<String>();
    BufferedReader br = null;

    try {

        String sCurrentLine;
        br = new BufferedReader(new FileReader(file));
        while ((sCurrentLine = br.readLine()) != null) {
            String test = sCurrentLine;
            array.add(test);

        }

    } catch (IOException e) {
        System.out.println("not diese!");

    } finally {
        try {
            if (br != null)
                br.close();
        } catch (IOException ex) {
        }
    }
    return array;
}

现在,我将 ArrayList 中的所有行放入 jTextArea 中,这向我显示了类似的内容:

PK����?����^��S?��3��� z_��
%�Q Tl?7��+�;� �fK��N��:k�����]�Xk,������U"�����q��\����%�Q#4x�|[��� o� S{��:�aG�*s g�'.}���n�X����5��q���hpu�H���W�9����h2��Q� ���#���@7(�@����F!��~��?����j�?\xA�/�Rr.�v�l�PK�bv�=

文本字段包含:

SELECTION:
----------
By clicking the CTRL Key and the left mouse button you go in the selection mode.
Now, by moving the mouse, you paint a rectangle on the map.

DOWNLOAD:
---------
By clicking on the download button, you start the download.
The default location for the tiles to download is: <your home>

我确信该文件存在! 有谁知道问题是什么?我的“getResource”正确吗?

最佳答案

根据输出,我怀疑您的代码实际上读取了 JAR 文件本身(因为它以 PK 开头)。为什么不使用下面的代码来读取文本文件:

Main.class.getResourceAsStream("/readme.txt")

这将为您提供文本文件的InputStream,而无需打开 JAR 文件等麻烦。

然后,您可以将 InputStream 对象传递给 readFileToArray 方法(而不是 File 对象)并使用

br = new BufferedReader(new InputStreamReader(inputStream));

其余代码不需要任何更改。

关于java - Main.class.getResource() 和 jTextArea,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15655548/

相关文章:

java - 如何将java(awt)代码转换成jsp代码

java - android.R.layout.simple_spinner_dropdown_item 和 android.R.layout.simple_spinner_item 的区别

windows - 解释java运行时检测到的 fatal error EXCEPTION_ACCESS_VIOLATION

c++ - 如何从 C++ 文件中读取字符串和相应的 int?

c# - Response.TransmitFile 传输完成后删除

java - android 内部存储写入文件后没有文件

java - 如何在没有项目的情况下降级jar文件的版本?

Java 默认构造函数

java - JFrame 未正确加载

java - 在 JComboBox 中使用向上/向下箭头滚动时,它不应该更新显示所选项目的顶部图 block