adding image in java swing [duplicate] - java

I need to get a resource image file in a java project. What I'm doing is:
URL url = TestGameTable.class.getClass().
getClassLoader().getResource("unibo.lsb.res/dice.jpg");
The directory structure is the following:
unibo/
lsb/
res/
dice.jpg
test/
..../ /* other packages */
The fact is that I always get as the file doesn't exist. I have tried many different paths, but I couldn't solve the issue.
Any hint?

TestGameTable.class.getResource("/unibo/lsb/res/dice.jpg");
leading slash to denote the root of the classpath
slashes instead of dots in the path
you can call getResource() directly on the class.

Instead of explicitly writing the class name you could use
this.getClass().getResource("/unibo/lsb/res/dice.jpg");

if you are calling from static method, use :
TestGameTable.class.getClassLoader().getResource("dice.jpg");

One thing to keep in mind is that the relevant path here is the path relative to the file system location of your class... in your case TestGameTable.class. It is not related to the location of the TestGameTable.java file.
I left a more detailed answer here... where is resource actually located

Related

How do I get the folder name from a String containing the Absolute file path in android?

Path name is : /storage/emulated/0/Xender/video/MyVideo.mp4
I am able to get last file name [MyVideo.mp4] from path using
String path="/storage/emulated/0/Xender/video/MyVideo.mp4";
String filename=path.substring(path.lastIndexOf("/")+1);
https://stackoverflow.com/a/26570321/5035015
Now i want to extract path [/storage/emulated/0/Xender/video] from this path.
I have one use of this path in my code so that i want to do this like this.
How can i do this?
Any help will be appreciated.
new File(path).getParentFile().getName() should work.
With regards to your current code, don't implement your own path parser. Use File.
Also note that this has nothing to do with Android specifically; this is a general Java question.

Velocity's FileResourceLoader can't find resources

I use Velocity in order to load email templates. Those templates are first downloaded from the FTP server and then saved as temporary files.
However, when I try to load the template I get an exception:
org.apache.velocity.exception.ResourceNotFoundException: Unable to find resource 'C:\Users\someUsername\AppData\Local\Temp\template1526050996884865454.html'
And I'm sure the file is there and it's not damaged.
That's how I try to load the template:
template = velocityEngine.getTemplate(tempFile.getCanonicalPath());
Here's the velocity.properties file that I load (and I've checked that the properties are properly initialized!)
file.resource.loader.class=org.apache.velocity.runtime.resource.loader.FileResourceLoader
file.resource.loader=file
file.resource.loader.path=.
So where lies the problem? Is it because AppData folder is hidden by default?
I think there's a design flaw in the Velocity FileResourceLoader. Basically if your file.resource.loader.path is anything other than an empty string, it'll mangle any absolute paths handed to it as the file. Additionally it has Unix/Linux-specific code to "nip off" (paraphrasing the actual code comment) an absolute file-path handed to it (Giving a broken absolute path re-rooted to the current path setting).
Solution 1:
Set the file.resource.loader.path to an empty string (prior to init()) and use absolute file-paths as the file parameter
ve.setProperty("file.resource.loader.path", "");
ve.init();
Template template = ve.getTemplate("C:\\Users\\someUsername\\AppData\\Local\\Temp\\template1526050996884865454.html");
Solution 2: Set the path to be the common root for your temp files and only hand it paths relative to that:
ve.setProperty("file.resource.loader.path", "C:\\Users\\someUsername\\AppData\\Local\\Temp");
ve.init();
Template template = ve.getTemplate("template1526050996884865454.html");
Ultimately I think the FileResourceLoader class would be better if it detected any absolute path handed to it as a file-name and not try to mash the path setting into it.
In addition to #MOles's answer, there is a third solution.
Solution 3: Configure more than one file resource loader: one for absolute resources and one for relative ones. Something like this:
resource.loader=absolute-file, relative-file
absolute-file.resource.loader.class=org.apache.velocity.runtime.resource.loader.FileResourceLoader
absolute-file.resource.loader.path=
relative-file.resource.loader.class=org.apache.velocity.runtime.resource.loader.FileResourceLoader
relative-file.resource.loader.path=.
This will allow files to be loaded either relatively or absolutely, since FileResourceLoader evidently gets confused when you try to use a single instance for either type of path.

Use of java.lang.Class.getResources

I've seen some posts on using java.lang.Class.getResources() and java.lang.Class.getResourcesAsStream() on SO today. Somehow, I still have confusion.
I have a Jar file that contains this structure (resources/test.xml)
This jar file is on the classpath of my application, and when I call below piece of code, it returns null, i.e. value of mappingURL is null.
URL mappingURL = this.getClass().getResource("/resources/test.xml");
However when I store the XML file in exploded format on the classpath i.e. by creating a directory "resources" and storing mapping.xml inside, it works.
I'm using this URL for reading the content of the "test.xml" file later.
Does that mean, getResources() is not the appropriate method for reading the files from inside a Jar? I didn't understand why mappingURL is null when file (test.xml) is present in the Jar file?
The getResource() method will return null if it cannot find the resource. You are prefixing the resource with a / which means that it is trying to look in the folder. You should be able to remove the leading / and achieve your intended result.
Here is the getResource() method description from the documentation:
Finds the resource with the given name. A resource is some data (images, audio, text, etc) that can be accessed by class code in a way that is independent of the location of the code.
The name of a resource is a '/'-separated path name that identifies the resource.
This method will first search the parent class loader for the resource; if the parent is null the path of the class loader built-in to the virtual machine is searched. That failing, this method will invoke findResource(String) to find the resource.
this.getClass().getResource("/resources/test.xml");
That should work, provided that the class file you are starting with is also in the same JAR file.
Does that mean, getResources() is not the appropriate method for
reading the files from inside a Jar?
This is correct. If your resource will be bundled in a jar, you always want to use getResourceAsStream().
A single line later and you can start reading the file:
BufferedReader reader = new BufferReader(InputStreamReader(getResourceAsStream("/test.xml")));
reader.readLine();
//...

getResource with parent directory reference

I have a java app where I'm trying to load a text file that will be included in the jar.
When I do getClass().getResource("/a/b/c/"), it's able to create the URL for that path and I can print it out and everything looks fine.
However, if I try getClass().getResource(/a/b/../"), then I get a null URL back.
It seems to not like the .. in the path. Anyone see what I'm doing wrong? I can post more code if it would be helpful.
The normalize() methods (there are four of them) in the FilenameUtils class could help you. It's in the Apache Commons IO library.
final String name = "/a/b/../";
final String normalizedName = FilenameUtils.normalize(name, true); // "/a/"
getClass().getResource(normalizedName);
The path you specify in getResource() is not a file system path and can not be resolved canonically in the same way as paths are resolved by File object (and its ilk). Can I take it that you are trying to read a resource relative to another path?

ServletContext not giving me real path when i want to go up level directory up

Why does ServletContext#getRealPath() not return me correct path if i use ../
This code works :-
System.out.println(context.getRealPath("/"));
This one doesn't :-
System.out.println(context.getRealPath("/.."));
How can i get one level up directory from getRealPath()?
Why does ServletContext#getRealPath() not return me correct path if i use "../":
To help protect you against requests that use ".." tricks to fetch content that they are not supposed to see; e.g. something like "../../../../../etc/passwd".
If you want to refer to a directory outside of the servlet context, you will need to create the path another way.

Categories

Resources