Java JCombobox在jar上不工作
我有一个应用程序,它用文本文件(.db)的内容填充JComboBox。在IDE上一切正常,但是在创建.jar时,JComboBox上没有显示任何内容 代码如下:Java JCombobox在jar上不工作,java,swing,jcombobox,embedded-resource,Java,Swing,Jcombobox,Embedded Resource,我有一个应用程序,它用文本文件(.db)的内容填充JComboBox。在IDE上一切正常,但是在创建.jar时,JComboBox上没有显示任何内容 代码如下: private void fill(String type) throws FileNotFoundException { BufferedReader input = null; // used to read file content try { input = new BufferedReader(
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));
非常感谢您的帮助:)到部署时,这些资源可能会成为一个重要的资源。在这种情况下,必须通过
URL
而不是File
访问资源。请参阅标签,以获取形成URL
的方法。如果文件要放在jar中,file
将不起作用。您需要使用classloader.getResourceAsStream(“/path/to.db”)
而不是使用classloader构建输入流,然后使用缓冲读取器读取行?我试过了,但没有成功。如果有助于解决问题,请告诉我。