I am beginner with Java and I have tried to make my app better. So I have a method to fill the jcombobox with items from text file. The method is
private void fillComboBox(JComboBox combobox, String filepath) throws FileNotFoundException, IOException {
BufferedReader input = new BufferedReader(new FileReader(filepath));
List<String> strings = new ArrayList<String>();
try {
String line = null;
while ((line = input.readLine()) != null) {
strings.add(line);
}
} catch (FileNotFoundException e) {
System.err.println("Error, file " + filepath + " didn't exist.");
} finally {
input.close();
}
String[] lineArray = strings.toArray(new String[]{});
for (int i = 0; i < lineArray.length - 1; i++) {
combobox.addItem(lineArray[i]);
}
}
And I am using it correctly
fillComboBox(jCombobox1, "items");
the text file with items is in my root directory of netbeans project. It works perfectly when running the app from netbeans. But when I build the project and create .jar file. It does not run. I tried to run it from comand line. This is what I got.
java.io.FileNotFoundException: items(System cannot find the file.)
How to deal with this? I didnt found anything. I dont know where is problem since it works nice in netbeans. Thank you very much for any help.
Is the .jar file in the same root directory?
Your exported .jar file might be working from a different directory, and not be able to find the text file.
Try placing the exported Jar in the same directory as the text file.
My example:
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
public class test {
public static void main(String[] args) throws FileNotFoundException, IOException{
JComboBox box = new JComboBox();
fillComboBox(box, "C:\\path\\test.txt");
JOptionPane.showMessageDialog(null, box);
}
private static void fillComboBox(JComboBox combobox, String filepath) throws FileNotFoundException, IOException {
BufferedReader input = new BufferedReader(new FileReader(filepath));
List<String> strings = new ArrayList<String>();
try {
String line = null;
while ((line = input.readLine()) != null) {
strings.add(line);
}
} catch (FileNotFoundException e) {
System.err.println("Error, file " + filepath + " didn't exist.");
} finally {
input.close();
}
String[] lineArray = strings.toArray(new String[] {});
for (int i = 0; i < lineArray.length - 1; i++) {
combobox.addItem(lineArray[i]);
}
}
}