【发布时间】:2018-08-24 15:31:48
【问题描述】:
我有一个应用程序用文本文件(准确地说是.db)的内容填充 JComboBox。在 IDE 上一切正常,但是在创建 .jar 时,JComboBox 上没有任何显示。
代码如下:
private void fill(String type) throws FileNotFoundException {
BufferedReader input = null; // used to read file content
try {
input = new BufferedReader(new FileReader("pack"+ File.separator +type+".db")); // loading the file based on previous box (see image).
} catch (FileNotFoundException ex) {
Logger.getLogger(Calc.class.getName()).log(Level.SEVERE, null, ex);
}
try {
String line = null;
while (( line = input.readLine()) != null){
type_list.addItem(line); // adding to my JComboBox
}
input.close();`
如前所述,在 netbeans IDE 上一切正常,我得到以下信息
但是在 .jar 上我得到以下信息:
我尝试从 inputStream 读取文件,但没有成功。我正在用我的应用程序编译 .db 文件,但这对我来说不是强制性的(我可以单独拥有 .jar+ db 文件)。
谢谢!!!
--------------------编辑-------------- -----
我用
解决了这个问题 InputStream is = this.getClass().getResourceAsStream("file.db");
BufferedReader br = new BufferedReader(new InputStreamReader(is));
非常感谢您的帮助:)
【问题讨论】:
-
如果文件要放在 jar 中,
File将不起作用。您需要改用classloader.getResourceAsStream("/path/to.db") -
您的意思是用类加载器构造一个 InputStream,然后使用缓冲读取器读取行?我试过这个没有成功。
标签: java swing jcombobox embedded-resource