Reputation: 7074
I have a file that I packaged in my JAR file, but I can't figure out how I would read the text file and store it into a String variable. Any ideas anyone?
Upvotes: 0
Views: 89
Reputation: 5475
This approach would work for any jar file, even if it's not in your current project/library/classpath:
String myJarFilename ="C:\\path\\to\\myfile.jar";
JarFile jarFile = new JarFile(myJarFilename);
JarEntry jarEntry = jarFile.getJarEntry("mytextfile.txt");
if (jarEntry != null)
{
InputStream is = jarFile.getInputStream(jarEntry);
// do normal stuff here to read string from inputstream
InputStreamReader isr = new InputStreamReader(is);
byte[] charArr = new byte[2048];
int bytesRead = 0;
StringBuffer sb = new StringBuffer();
while (bytesRead = is.read(charArr, 0, 2048) > 0)
{
sb.append(charArr, 0, bytesRead);
}
String fileContent = sb.toString();
}
Upvotes: 1
Reputation: 398
You can use a URLClassLoader to access resources in a JAR archive.
Upvotes: 0
Reputation: 10891
I would recommend
java.lang.Class#getResource(java.lang.String) or java.lang.Class#getResourceAsStream(java.lang.String)
Upvotes: 2