I 've developed an eclipse plugin and in that I have a java file trying to read directories and then populate result accordingly.
When I try to run the file from eclipse itself through Run>Java application , it gives me proper result but as soon as I try to run the same through Eclipse Application, it is throwing NullPointerException because unable to find the directory.
I tried the following ways-
Suppose , I have a package as -
Package - com.test.abhishek.file.java.TestWork.java
Directories - com.test.abhishek.file.java.Dir1
com.test.abhishek.file.java.Dir2
Now in TestWork.java-
InputStream is = HelpContentView.class.getResourceAsStream("/"+dirName);**
The above line is getting failed.
How should I keep my directory and where so that it will run as an eclipse plug-in as well.
Tried to find the class path by
TestWork.class.getClassLoader().getResource("").getPath() and getting the output as /
So now where should I dump my directories to ressolve.
Just trying to understand what you are doing. You have a directory within your source structure that you want to get? Eclipse plugins are normally placed in the /plugins directory jar'ed up. This means you either A) need to bundle your resources with your plugin using build.properties, or put them somewhere else in the file structure and access it using normal File IO mechanisms.
If you are creating a plugin you most likely want to use Bundle.getEntry instead
public void start(BundleContext context) {
Bundle bundle = context.getBundle();
InputStream in = bundle.getEntry("/"+dirName").openStream();
}
It looks like you need the findEntries API.
For some example code, check out the related question (and answer) at How to test if a URL from an Eclipse bundle is a directory?
Related
Both class.getResource(FILE_NAME) and class.getClass().getClassLoader().getResource(FILE_NAME) run perfectly inside my eclipse but the same code getting failed to locate the file which is inside the jar file, when run as an executable jar in windows machine.
I have gone through all related links available for this problem (well, not exactly the same issue but 90% in sync), asked for solution but no reply came from any of those posts, so I'm posting my issue as a separate question hoping for help on this.
In total, 4 cases I have ran to resolve but none worked so far and I'm out of ideas now.
class.getClass().getClassLoader().getResource("/resources/readme.txt");
class.getResource("/resources/readme.txt");
class.getClass().getClassLoader().getResource("resources/readme.txt");
class.getResource("resources/readme.txt");
Ouf of all the above 4 cases, only 2 cases ran successfully in eclipse which are as mentioned below.
class.getResource("/resources/readme.txt");
class.getClass().getClassLoader().getResource("resources/readme.txt");
The other 2 cases just throwing me Exception in thread "main" java.lang.NullPointerException
Coming to the executable jar, all 4 cases are throwing me the Exception in thread "main" java.lang.NullPointerException.
So I have created a folder named resources where my jar is residing and placed my files inside this folder and ran the jar. Now the jar is running without any issues referring to the files inside the resources folder I created. So wherever I run this jar (windows, linux etc.,) I need to create a resources folder and place my files under the folder. Now the question is, can it be possible to make my jar refer the resources folder which is inside the jar itself?
Any help on this is much appreciated!
To get your txt file:
File yourFileIsHere = new File("resources/readme.txt");
Where put your file?
In the same location of your jar, example:
myapp/yourjar.jar
myapp/resources/readme.txt
If you want read file inside of your "src" folder:
InputStream yourInputStream = new YourClass().getClass().getClassLoader().getResourceAsStream("readme.txt");
If you are using Spring:
org.springframework.util.ResourceUtils.getFile("classpath:readme.txt")
Otherwise:
import com.google.common.io.Resources
byte[] byteSource = Resources.asByteSource(Resources.getResource("readme.txt")).read()
method class.getClass().getClassLoader().getResource() may take 3 prefixes: url:, classpath: and file: each prefix tells what is your base of search. If you want to search inside your jar use classpath: prefix. That tells your classloader to search everywhere within your classpath. Here is one example how to deal with it with Spring tools. Look also at ResourceLoader class in Spring
In Eclipse Luna I have a Dynamic Web Project (with default build settings) on Apache Tomcat 8.0. In the project, I have a JSP loader.jsp that calls a method in a Java class FileLoader that returns a String value for the location of a non-config txt file (lets call it key.txt).
My issue is that I am getting a null value for the file location when FileLoader tries to get key.txt and return its location.
Here is an idea of what I've tried and failed with:
In FileLoader constructor I pass it String "key.txt" as a value and it has a method called get getKeyPath() that returns the file path. I use the following in getKeyPath() to get the file path:
String path = this.getClass().getClassLoader().getResource("key.txt").getFile();
The path variable is returned to the calling object. Here is how I call getKeyPath() in loader.jsp:
String keyPath = new FileLoader("key.txt").getKeyPath();
My issue is that a NullPointerException is thrown in FileLoader when getKeyPath() tries to set the path value. I am lost because this happens no matter where I put the physical "key.txt" in my project directory or at file paths that should be recognized by my project. In my project I have tried the above code with key.txt at the following paths (assume the root folder for my project in Eclipse is called PRO):
PRO/build/classes
PRO/build
PRO/WebContent/WEB-INF/lib
PRO/WebContent(where loader.jsp is located)
PRO/Java Resources/src (Tomcat Install)
Dir>/lib /bin
I got the same NullPointerException for all attempts. Once I resorted to the Tomcat directories I realized I needed help.
Is there something else I need to do so "key.txt" can be loaded in the way I want? Am I doing this completely wrong? I can post screenshots if that would make answering this easier.
As an aside, due to application requirements, I'd prefer that loader.jsp not load key.txt directly. Of course, I'll have to do that if what I'm trying is not possible.
Please note that I am trying to do this in an Eclipse Dynamic Web Project so there is no "bin" folder like a standard Java project. Finally, I'd prefer not to make any build config changes in Eclipse but of course I will if I have to.
Separate out the initialization and calling of the method into two separate lines.
Problem is not that file is not loaded but rather that at the time .getKeyPath(); is called object initisation is not done and that the reason for NullPointer
So change to this :
FileLoader FileLoader fileLoader = new FileLoader("key.txt");
String keyPath = fileLoader.getKeyPath();
Yesterday, I had a problem because I couldn't manage to open a xml file (it owuld give me a FileNotFoundException) located in the ressources folder of my .jar file, which I managed to open on eclipse using the following lines of code. You can see my old problem here. This was my code with the problem :
File xmlFile = new File("ressources/emitter.xml");
ConfigurableEmitter emitter = ParticleIO.loadEmitter(xmlFile);
Someone told me it that one way was to use getClassLoader().getRessourceAsStream method to open a xml file in a .jar file that was exported
InputStream i= this.getClass().getClassLoader().getResourceAsStream("ressources/emitter.xml");
ConfigurableEmitter emitter = ParticleIO.loadEmitter(i);
Unfortunately, that solution only works when I export my project into a .jar file, so if I want to go back debugging my program, I have to take the old code that would only works on eclipse.
My question is: is there any better way to do this without having to change my code if I want to export it or if I want to debug it?
Thank you
edit :
Thank you all, it works perfectly fine now
my problem was that I put my ressources folder like that :
+project
+src
+ressources
+emitter.xml
InputStream i= this.getClass().getClassLoader().getResourceAsStream("/ressources/emitter.xml");
The above should work in both cases (Note is is /resources/.... This is assuming say your directory structure is below:
MyProject
+src
+ressources
emitter.xml
Place the file alongside your source files, then you can use the getResourceAsStream() method in both cases. Don't forget to update the path (which should be the package name of your class, but with slashes instead of dots).
My question is: is there any better way to do this without having to
change my code if I want to export it or if I want to debug it?
Yes, use Maven. Maven will handle that and it hooks into Eclipse beautifully (NetBeans too!) What you do is place the resource in src/main/resources and then you can have Eclipse run the test goal of the Maven project or you can just run mvn test from the command line. Another advantage of using Maven here is that you can also have src/test/resources/emitter.xml which overrides the one in src/main with environment-specific test instructions and it won't affect your deployment.
InputStream i= getClass().getClassLoader().getResourceAsStream("ressources/emitter.xml");
or
InputStream i= getClass().getResourceAsStream("/ressources/emitter.xml");
(note the absolute positioning)
both work when the class is in the same jar, on the same class path.
In the jar the names must be case sensitive, but as the jar already works. Ensure that the ressources directory is on the class path too, or copied to the target directory.
As "ressources" is probably configured yourself (not named "resources" as in English), you probably need to add it to the build somehow.
I have a project that uses the normal Maven structure, e.g.
module
\ src
\ main
- java
- resources
\ test
- java
- resources
etc. Under test/resources, I'd like to keep a set of test input files for a parser I'm writing, then run all files in the directory through the test suite. As written now, the test code works from the command line, but fails when run through the Eclipse JUnit plugin:
File file = new File("src/test/resources");
file.list();
(I'm actually using a FilenameFilter, but I'm trying to simplify.)
The problem, after poking through the unit test with a debugger, turns out to be that the File I'm constructing points to /path/to/workspace/myproj/src/test/resources, whereas the actual files reside in /path/to/workspace/myproj/modulename/src/test/resources (it's a Maven multi-module project). Apparently, this isn't a problem when running mvn test from the command line.
I guess my question is two-fold: one, am I doing this wrong? I see a lot of people using the class loader to discover resources, as in this question, but I don't want all the resources of a particular type, just one directory under test/resources. Two, if this isn't a terrible idea in the first place, do I have a configuration error (e.g. it "should" work)? Is it Eclipse's fault, a Maven problem, or what?
One trick would be to place a file in resources with a known name, get the URI of this file through the classloader, then construct a File from this URI, then get the parent, and list() the contents of that directory. Kind of a hack, but it should work.
So here's what the code should look like, but place a file called MY_TEST_FILE (or whatever) in test/src/resources
URL myTestURL = ClassLoader.getSystemResource("MY_TEST_FILE");
File myFile = new File(myTestURL.toURI());
File myTestDir = myFile.getParentFile();
Then you have access to the directory you're looking for.
That said, I'd be surprised if there's not a more 'maven-y' way to do it..
Just for completeness, wanted to point out the way to get this without having to grab the current instance of the ClassLoader, using ClassLoader#getSystemResource. This example does the work without having to place a file at the top.
//Obtains the folder of /src/test/resources
URL url = ClassLoader.getSystemResource("");
File folder = new File(url.toURI());
//List contents...
Try this?
1)put test data files into the same package structure as you test classes. That is, if you have a test class named Apple in src/test/java/com/fruits, you test data file will be in src/resources/java/com/fruits.
2) When the files are compiled both the class and the data file should be in target/test-classes/com/fruits. If this is the case, in you code, you can obtain the file this way "this.getClass().getResourceAsStream("myFile")"
put desired resource into /src/test/resources/lipsum.pdf
find it's full path using
String fileName = ClassLoader.getSystemResource("lipsum.pdf").getFile();
I had problems while finding the path of file(s) in Netbeans..
Problem is already solved (checked answer).
Today I noticed another problem: When project is finished,
I have to execute the generated .jar to launch the program, but it doesn't work because an error occurs: NullPointer (where to load a file) when accessing/openning jar outside Netbeans.
Is it possible to open a file with the class file in Java/Netbeans which works in Netbeans and even in any directory?
I've found already some threads about my problem in site but none was helpful.
Code:
File file = new File(URLDecoder.decode(this.getClass().getResource("file.xml").getFile(), "UTF-8"));
The problem you have is that File only refer to files on the filesystem, not files in jars.
If you want a more generic locator, use a URL which is what getResource provides. However, usually you don't need to know the location of the file, you just need its contents, in which case you can use getResourceAsInputStream()
This all assumes your class path is configured correctly.
Yes, you should be able to load a file anywhere on your file system that the java process has access to. You just need to have the path explicitly set in your getResource call.
For example:
File file = new File(URLDecoder.decode(this.getClass().getResource("C:\\foo\\bar\\file.xml").getFile(), "UTF-8"));