I have read many posts on here and done many Google searches but I am still unable to read a file from another java package within my current project.
In one of my classes I have the following code, however the input stream is always null. I have tried using the context class loader, as well as many other solutions but to no avail.
InputStream is = this.getClass().getResourceAsStream( "opcodes.txt" );
System.out.println(is);
Another attempt was:
InputStream is = ClassName.class.getResourcceAsStream("/resources/opcodes.txt");
which also returned null.
Any help or explanation for why I can not find the file within a resource package would be great.
p.s. I am using eclipse if that makes a difference.
EDIT: If I use an OpenFileDialog to find the file, I am able to open and read it, so the file does exist and is not corrupt.
The documentation of the getResourceAsStream() method, found here:
http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getResourceAsStream(java.lang.String)
says that:
"
Before delegation, an absolute resource name is constructed from the given resource name using this algorithm:
If the name begins with a '/' ('\u002f'), then the absolute name of the resource is the portion of the name following the '/'.
Otherwise, the absolute name is of the following form:
modified_package_name/name
Where the modified_package_name is the package name of this object with '/' substituted for '.' ('\u002e').
"
Your first attempt would have succeeded had the resource been located within the same package as the one the class you're invoking the method from is located. Your second attempt fails because, like the documentation says, the name of the file you give ("/resources/opcodes.txt") is replaced by "resources/opcodes.txt". I guess it means that the method will now search for package resources WITHIN the package where the class that invokes the method is located and not outside of it. Since you don't have such an inner package, the method returns null.
A workaround would be to define a class within the package where your resource is located. That class could be empty for all you care. Just call:
ClassWithinResourcePackage.class.getResourceAsStream("opcodes.txt");
from within the class you currently invoke the method from, and it works.
I also tried to use the ".." syntax I know from command line, but it doesn't work. I think the documentation implies the method is looking for a file within the same package only.
Resource files are generally placed in src/main/resources/ directory in your project. These resources are also packed in the jar alongside the compiled class files with .class extension.
I have created a sample maven project with the directory hierarchy discussed above.
The resource file sample-resource.properties can be accessed in the program as below:
package temp;
import java.io.InputStream;
import java.util.Scanner;
public class ResourceTest {
public static void main(String[] args) {
InputStream inputStream = ResourceTest.class.getResourceAsStream("/sample-resource.properties");
Scanner scanner = new Scanner(inputStream);
while (scanner.hasNext()) {
System.out.println(scanner.nextLine());
}
}
}
This would read and print the contents of the resource file:
Related
I'm working on an application that needs to be able to do some analysis on Java code; some through the text and some through reflection. The user should be able to input a directory and the program will pull all .java and .class files from it. I have no problem with the .java files but when I try getting the class of the .class file it doesn't work.
I've looked at using ClassLoader with URL. What I've been able to find so far has given me this
URL url = this.openFile().toURI().toURL();
URL[] urls = new URL[]{url};
ClassLoader cl = new URLClassLoader(urls);
Class cls = cl.loadClass(this.path);
return cls;
path is just a string containing the actual path of the .class file in question, e.g. Users/me/Documents/Application/out/production/MyPackage/MyClass.class. From what I understand from my own reading, this method ties me to knowing the package structure of the input, but in general I don't. All I have is the absolute path of the .class file. Is there a way, just using this path (or some simple transformation of it) that I can load into my program the actual MyClass class object and start doing reflection on it?
You have 2 options:
Use a byte code library to first read the file, so you can find out what the actual class name is.
E.g. in your example it is probably MyPackage.MyClass, but you can't know that from the fully qualified file name.
Implement your own ClassLoader subclass, and call defineClass(byte[] b, int off, int len).
Recommend using option 2.
I'm working with Java 1.8. I'm trying to create a folder if not exists using this method:
private void createDirIfNotExists(String dirChemin) {
File file = new File(dirChemin);
if (!file.exists()) {
file.mkdirs();
}
}
This works when I give it the right path, for example this creates a folder if it doesn't exist
createDirIfNotExists("F:\\dir")
But when I write an incorrect path (or name), it didn't give me any thing even an error! for example :
createDirIfNotExists("F:\\..?§;>")
So I want to improve my method, so it can create the folder if it doesn't exist by making sure that my path is right, otherwise it should give me an error message.
mkdirs() also creates parent directories in the path this File represents.
javadocs for mkdirs():
Creates the directory named by this abstract pathname, including any
necessary but nonexistent parent directories. Note that if this
operation fails it may have succeeded in creating some of the
necessary parent directories.
javadocs for mkdir():
Creates the directory named by this abstract pathname.
Example:
File f = new File("non_existing_dir/someDir");
System.out.println(f.mkdir());
System.out.println(f.mkdirs());
will yield false for the first [and no dir will be created], and true for the second, and you will have created non_existing_dir/someDir
I have a class XYZ in application that is executed as jar in any directory. I want to find the current directory path in which jar is executing for this I have used following code.
String path = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath()
I write this code in public constructor of XYZ class but it is not working though I am using it since long time it works fine, but now it is not returning the current directory path.
please mark and suggest what is going wrong in this.
When you execute your statement within "this" - it means that you are trying to locate current instance of the class but you need to find the class itself.
In your case you can use this:
String path = XYZ.class.getProtectionDomain().getCodeSource().getLocation().getPath();
String decodedPath = URLDecoder.decode(path, "UTF-8");
It will give you the path you are looking for and will solve issues with whitespaces and special characters inside this path.
In case you are doing this for Linux it might be useful to use:
URLDecoder.decode(ClassLoader.getSystemClassLoader().getResource(".").getPath(), "UTF-8");
...but now it is not returning the current directory path.
It shouldn't return the current directory path. It should return the path of the jar file the class is coming from, or the root folder where the class files are loaded from (if not packed in a jar). It might and it might not be the current folder.
Calling
this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath()
will try to locate the path the class of the current instance (this) is coming from.
Make sure that the Class you start from is part of the jar file. E.g. do not use this but use an explicit class which you're sure is from the jar file, e.g.
SomeClass.class.getProtectionDomain().getCodeSource().getLocation().getPath()
Also note that this won't work if you start the application from your IDE in which case the result would be the bin folder (the root folder of compiled class files).
return new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath());
OR
return new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath().toURI());
I have a unit test package in which I keep a few txt files. These get loaded via getClass().getResource(file); call and it works just fine. I added into the same folder a csv file, and if I supply its name as the parameter i.e. getClass().getResource("csvFile.csv"); I get null... any ideas why?
When you use
getClass().getResource("csvFile.csv");
it looks relative to the class.
When you use
getClass().getClassLoader().getResource("csvFile.csv");
it looks in the top level directories of your class path.
I suspect you want the second form.
From Class.getResource(String)
Before delegation, an absolute resource name is constructed from the given resource name using this algorithm:
If the name begins with a '/' ('\u002f'), then the absolute name of the resource is the portion of the name following the '/'.
Otherwise, the absolute name is of the following form:
modified_package_name/name
Where the modified_package_name is the package name of this object with '/' substituted for '.' ('\u002e').
As you can see the directory translation of the package name of the class is used.
For example, I have a maven project where the code is under src/main/java. My resources directory src/main/resources
I add csvFile.csv to my resources directory which will be copied to my class path.
public class B {
B() {
URL resource = getClass().getClassLoader().getResource("csvFile.csv");
System.out.println("Found "+resource);
}
public static void main(String... args) {
new B();
}
}
which prints
Found file:/C:/untitled/target/classes/csvFile.csv
This is in the area built by maven from the resources directory.
Have you tried getClass().getClassLoader().getResourceAsStream(file)
This in turn returns an inputstream which you can use to access the file
When I create ImageIcon class objects I use the following code:
iconX = new ImageIcon (getClass().getResource("imageX.png"))
The above code works correctly either in an applet or a desktop app when the .png is in the same folder of the class.
The question is: how to avoid a NullPointerException when the .Png is in another folder? Or how load the image in the object ImageIcon when it is in a different location to the class?
I don't understand how this method works, if anyone can help me I appreciate it. Thanks!!
Take a look at this - Class#getResource(java.lang.String)
Please click the link above and read the docs and follow to understand what's going on.
It says -
If the name begins with a '/', then the absolute name of the resource is the portion of the name following the '/'.
and
Otherwise, the absolute name is of the following form:
modified_package_name/name
Where the modified_package_name is the package name of this object with '/' substituted for '.'.
So, if this object (where you call getResource) is in package /pkg1 (/ meaning pkg1 is right under the root of the classpath) and you used "imageX.png" then the result would be pkg1/imageX.png which is correct because that's where the image is located at.
But, if we moved the resource (imageX.png) to some other package /pkg2 and you called the method same way then the result would still be pkg1/imageX.png but this time it would be incorrect because the resource is actually located in /pkg2. That's when you end up with NPE.
It's good to explicitly specify the full path of the resource starting from the root of the classpath. (e.g. "/pkg/imageX.png").
Hope this helps.
Simply supply the path to the resource.
So, if you put the image in "/resources/images" within your Jar, you would simply use
iconX = new ImageIcon(getClass().getResource("/resources/images/imageX.png"))
Essentially what you're saying is, class loader, please search your class path for the following resource.
If the image is internal (you want a location relative to your project, or perhaps packaged into your jar), do what mad programmer said:
iconX = new ImageIcon(getClass().getResource("/path/imageX.png"))
The path is relative, so path/ will be a folder in the same folder as your project (or packaged into your jar).
If you want an external image, simply hand ImageIcon constructor the path (ex. "C:/.../file.png"). This isn't recommended though, as it's better to use it as a resource.
For more info on the ImageIcon constructor, see here. for more info on loading class resources, see here (Javadoc links)