<分区>
我试图做的是在程序的 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 时,在我的资源文件夹中有我用于图标的图片,但没有文本文件。