java - 如何读取 JAR 中的文本文件?

标签 java file text jar embedded-resource

<分区>

我试图做的是在程序的 JAR 中存储一个文本文件(不会更改),以便可以读取它。文本文件的用途是它会被我的一个类读入,文本文件的内容将被添加到 JEditorPane。该文件基本上是一个教程,当用户点击阅读教程的选项时,文件内容将被读取并显示在弹出的新窗口中。

我有它的 GUI 部分,但就将文件存储在 JAR 中以便访问它而言,我不知所措。我读到过使用 InputStream 会起作用,但在尝试了一些方法之后我还没有让它起作用。

我还将图像存储在 JAR 中,用作 GUI 窗口的图标。这是通过以下方式实现的:

private Image icon = new ImageIcon(getClass()
    .getResource("resources/cricket.jpg")).getImage();

但是,这在尝试获取文件时不起作用:

private File file = new File(getClass.getResource("resources/howto.txt"));

这是我现在的类(class):

public class HowToScreen extends JFrame{

/**
 * 
 */
private static final long serialVersionUID = -3760362453964229085L;
private JEditorPane howtoScreen = new JEditorPane("text/html", "");
private Image icon = new ImageIcon(getClass().getResource("resources/cricket.jpg")).getImage();
private BufferedReader txtReader = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("/resources/howto.txt")));

public HowToScreen(){
    setSize(400,300);
    setLocation(500,200);
    setTitle("Daily Text Tutorial");
    setIconImage(icon);

    howtoScreen.setEditable(false);
    howtoScreen.setText(importFileStream());
    add(howtoScreen);
    setVisible(true);
}

public String importFile(){
    String text = "";
    File file = new File("howto.txt");
    Scanner in = null;

    try {
        in = new Scanner(file);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    while(in.hasNext()){
        text += in.nextLine();
    }

    in.close();
    return text;
}

public String importFileStream(){
    String text = "";
    Scanner in = new Scanner(txtReader);

    while(in.hasNext()){
        text += in.nextLine();
    }

    in.close();
    return text;
}
}

忽略 importFile 方法,因为它已被删除以支持将教程文件存储在 JAR 中,使程序完全独立,因为我对程序可以使用的空间有限制。

编辑: 在尝试了下面的所有建议之后,我检查了我的 JAR 是否将文本文件打包在其中,但事实并非如此。当用 7zip 打开 JAR 时,在我的资源文件夹中有我用于图标的图片,但没有文本文件。

最佳答案

您不能在 JAR 文件中使用 File。您需要使用 InputStream 来读取文本数据。

BufferedReader txtReader = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("/resources/mytextfile.txt")));

// ... Use the buffered reader to read the text file.

关于java - 如何读取 JAR 中的文本文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16953897/

相关文章:

java - 扩展 File 类,为用户通过网络 channel 透明地提供一致的文件系统方式

mysql - 从本地软件将数据导入远程 MySQL 的最佳文件格式

python - 在文本文件中搜索和排序

java - 通过 JScrollPane 异常行为重新调度 MouseEvent

java - java中的Unicode编码

java - 栈、堆和递归

java - 如何测试使用 HttpServletRequest 的休息服务?

javascript - 读/写 Windows 图像标签(关键字)

cocoa - 如何调整 NSTextField 的大小以适合它所包含的文本?

ruby-on-rails - 如何使用 Mongoid 执行 runCommand?