【发布时间】:2013-06-01 23:28:03
【问题描述】:
我试图做的是在程序的 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"));
这是我现在的班级:
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 是否正在打包文本文件” 聪明的举动。 :)
-
是的,我不完全确定为什么在我使用 Eclipse 导出 Runnable JAR 时不包含它。
-
“我用于图标的图片在那里,但不是文本文件。” 这必须在任何答案之前解决首先工作。以防万一在这方面有任何混淆。您可能 1) 显着编辑此问题.. 或 2) 就 Eclipse 构建中缺少的资源提出一个新问题。
标签: java file text jar embedded-resource