use*_*692 7 java text jar file embedded-resource
我试图做的是在程序的JAR中存储一个文本文件(不会改变),以便可以读取它.文本文件的目的是它将被我的一个类读入,文本文件的内容将被添加到JEditorPane.该文件基本上是一个教程,当用户点击选项阅读教程时,文件内容将被读取并显示在弹出的新窗口中.
我有它的GUI部分,但只要将文件存储在JAR中以便可以访问它,我就迷路了.我已经读过使用一个InputStream遗嘱,但在尝试了一些事情之后我还没有让它工作.
我还将图像存储在JAR中,以用作GUI窗口的图标.这完成了:
private Image icon = new ImageIcon(getClass()
.getResource("resources/cricket.jpg")).getImage();
Run Code Online (Sandbox Code Playgroud)
但是,这在尝试获取文件时不起作用:
private File file = new File(getClass.getResource("resources/howto.txt"));
Run Code Online (Sandbox Code Playgroud)
这是我现在的班级:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
忽略importFile方法,因为删除该方法有利于将教程文件存储在JAR中,使程序完全自包含,因为我限制程序可以使用多少空间.
编辑:在尝试下面的所有建议后,我检查了我的JAR是否正在打包文本文件,但事实并非如此.用7zip打开JAR时,在我的资源文件夹中,我用于图标的图片在那里,但不是文本文件.
Sri*_*ati 11
您不能在JAR文件中使用File.您需要使用InputStream来读取文本数据.
BufferedReader txtReader = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("/resources/mytextfile.txt")));
// ... Use the buffered reader to read the text file.
Run Code Online (Sandbox Code Playgroud)