Reading a text file from jar files
In my application there are many class files. I have made a jar file from these class files. The jar file executes well. My program reads from a text file and displays its contents while running. I have also included this text file in the jar file. But my program is not reading the text file from the jar file.
What should I do to read the text file from the jar file?
Thanks in advance.
Kishore.
Re: Reading a text file from jar files
You can use getResource(fileName) to create a URL for the file (this uses the ClassLoader which will search Jar files for resources), then get an InputStream from it, e.g. if file.txt is in a local Jar file you can read it like this:// Find file and make URL:
URL url = getClass().getResource("file.txt");
if (url != null) {
try {
// Read from URL input stream:
InputStream ins = url.openStream();
BufferedReader br = new BufferedReader(new InputStreamReader(ins));
String line = null;
while ((line = br.readLine()) != null) {
// do something with line;
}
}
catch(IOException ioe) {
System.out.println(ioe.getMessage());
}
}
Alternatively, you could use the ZipFile class, but it's more effort...
Dave
Re: Reading a text file from jar files
Thank you very much.
Kishore.