读取不在可运行jar中的主包中的文本文件 [英] Read text file that is not in the main package in a runnable jar

查看:239
本文介绍了读取不在可运行jar中的主包中的文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Swing Java程序,在包含不同类型的JSON的子文件夹的名为'res'的资源文件夹中读取* .txt文件。当我直接从Eclipse运行,一切都很好。如果我创建一个可执行的jar它不工作。我设法使它的工作与一个可怕的解决方案,把我所有的文本文件包在他们被叫。



要阅读他们,我使用这一行代码: / p>

  InputStream is = this.getClass()。getResourceAsStream(file +.txt); 

其中file是一个字符串。我以为这将在jar中搜索指定的文件,但显然不是。我试图将路径放在文件res / subfolder / name_of_file.txt和子文件夹/ name_of_file.txt上,但无效。
这是我的项目的结构

 项目
src
com.package
res
JSON_type1
JSON_type2
file.txt

从com.package,我有一个类必须从JSON_type2 / file.txt读取。除了将文本文件保存在子文件夹中的明显原因是,我的GUI将使用这些子文件夹的内容填充一个下拉列表。



从我的从其他问题汇总,getResourceAsStream()本来是我的解决方案,如果我想把我的文本文件保存在包中被调用的位置。除此之外,我发现了一些关于子类化的一些 ClassLoader 并覆盖 findResource()。如果可能,我想避免这种解决方案,因为我远不熟悉该类及其功能。



如果您需要更多信息,请告诉我们。



谢谢



PS:这个问题源于我之前的问题

  //添加前导/表示从class-path的根目录搜索
String file =/res/JSON_type2/file.txt;
InputStream is = this.getClass()。getResourceAsStream(file);


I have a Swing Java program that reads *.txt files in a resource folder called 'res' containing subfolders of different kind of JSONs. When I run directly from Eclipse, all is fine. If I create an executable jar it doesn't work. I managed to make it work with an horrifying solution, putting all my text files in the package where they are called.

To read them I use this line of code:

InputStream is = this.getClass().getResourceAsStream(file + ".txt");

where file is a string. I thought this would search in the jar the specified file but obviously not. I tried to put the path to the files, res/subfolder/name_of_file.txt and subfolder/name_of_file.txt but to no avail. Here is the structure of my project

Project
   src
      com.package
   res
      JSON_type1
      JSON_type2
         file.txt

From com.package, I have a class that must read from JSON_type2/file.txt. Besides the obvious reason to keep my text file organized in the subfolders is that my GUI will populates a drop down list with the content of those subfolders.

From what I've gather from other questions here, getResourceAsStream() would have been my solution if I wanted to keep my text files in the package where they are called. Other than that I found something about subclassing ClassLoader and overwriting findResource(). If possible I want to avoid this solution as I'm far from being familiar with that class and its functionalities.

Should you need more informations, let me know.

Thank you

P.S.: This question arose from my previous question here

解决方案

// added leading / to indicate search from root of class-path
String file = "/res/JSON_type2/file.txt";
InputStream is = this.getClass().getResourceAsStream(file);

这篇关于读取不在可运行jar中的主包中的文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆