I have a text file bundled inside a JAR, how do i access from my code that is also part of the jar?
So for example the package where my code is "com.test.services.LoadRunner.FireCollection" and the text file is also under that package. How do i access it?
Do you have access to that text file when you are running the unzipped code? How did you gain access? Presumably something like new File("myFile.txt")? Did that path work?
I always thought you are supposed to put files in their own folder and quote the path to that folder when you open the files.
Have you seen the examples in the Java Tutorials? (Try the "creating" page.)
If your file is in the package com.test.services.LoadRunner.FireCollection and the file needed is named fire.txt then you get the URI by doing this:
getResource will search from all the classpath starting points. Normally, you put resources like this under a folder of its own. Remember that this is a read only file, but useful when storing templates or default properties.
This works, as mentioned below, for resources on the classpath, but not on resources in a Jar. See Ernest addition.
There's a simple and straightforward answer to this: use the Class.getResource() family of methods. For example, if you have "/data/file.txt" in the jar file, then you can open that file for reading using something like
The nice thing about this is it works perfectly whether the files are in a JAR or not. If they're not, then it works as long as the parent of the data directory is on your classpath.
Edit: Ove's answer won't work if the file is in a JAR, although it can be used to find physical files on the classpath.
Aditya Sirohi wrote:
FileReader paramReader = new FileReader("com/test/services/LoadRunner/FireCollection/fire.txt"); and will this file be read if its inside com.test.services.LoadRunner.FireCollection package?
Not if the files are in a JAR, and only if the directory "com" is a subdirectory of the current working directory.
Use this instead: it will find a file anywhere on the classpath, even inside a JAR: