如何读取JAR中的文本文件?
我试图做的是在程序的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.
你的代码不会编译。 Class.getResource()
返回一个URL
,而File
没有带URL
作为参数的构造函数。
您可以使用.getResourceAsStream()
代替,它直接返回一个InputStream
,您只需要从该流中读取该文件的内容。
注意:如果找不到资源,这两个方法都返回null
:不要忘记检查…
尝试下一个(使用完整路径包):
InputStream inputStream = ClassLoader.getSystemClassLoader(). getSystemResourceAsStream("com/company/resources/howto.txt"); InputStreamReader streamReader = new InputStreamReader(inputStream, "UTF-8"); BufferedReader in = new BufferedReader(streamReader); for (String line; (line = in.readLine()) != null;) { // do something with the line }
文本文件的内容将添加到
JEditorPane
。
请参阅DocumentVewer
特别是JEditorPane.setPage(URL)
。
由于帮助是嵌入式资源,因此需要使用信息中详述的getResource(String)
获取URL
。 页面 。
..试过这个:
URL url = this.getClass().getResource("resources/howto.txt");
更改:
URL url = this.getClass().getResource("resources/howto.txt");
至:
URL url = this.getClass().getResource("/resources/howto.txt"); // note leading '/'