How to access an image in a different folder? - java

How would I access a picture in a different folder in Java? I have a series of pictures and they change based on user input, which is what x is for.
picture.setIcon(new ImageIcon("\\resources\\icons\\pictures\\"+x+".png"));
The images are located (from the .class files) in resources/icons/pictures, but the above code doesn't work. The value of x isn't the problem since it works as it should. Am I calling the pictures the right way?

Am I calling the pictures the right way?
Probably not. If they are (embedded) application resources they will typically be in a Jar and unavailable via the String based constructor of the ImageIcon (which expects the String equates to a File path).
For an embedded resources, access them by URL.
URL urlToImg = this.getClass().
getResource("/resources/icons/pictures/"+x+".png");
picture.setIcon(new ImageIcon(urlToImg));

You should be using forward slashes instead of backslashes I believe.
new ImageIcon("/resources/icons/pictures/"+x+".png")
This is the standard Java cross-platform way of denoting resource file paths. It still works on Windows - the Java runtime library handles the transaltion for you.

The images are located (from the .class files) in resources/icons/pictures
That's a problem. The system isn't interested in where the class file is, but from where you invoke a program.
Specifying a resource folder via command line,
java -jar myJar.jar C:\\home\\of\\the\\images
or via a property
java -jar myJar.jar -DImageHome=/foo/bar/images
or from a properties file is most flexible.
If you like to put the images into the jar, use Andrews suggestion, getClass ().getRessource ("...");
Btw: I know for sure, that forward slashes are portable. Backslashes, afaik, aren't.

Related

How to avoid hard code full path in Paths#get method

I want to save a copy of Primefaces UploadedFile to my project directory. I have been searching the internet for the solution, what I have found is using Paths#get method. The example given in this answer is Paths.get("/path/to/uploads");, the problem is, where is the exact path of /path/to/uploads? I can't find it. I mean where should I create the path /path/to/uploads? Under my project directory? but which folder? I solve this issue temporary by hard coding the full path like Paths.get("C:/uploads/");
FacesContext.getCurrentInstance().getExternalContext().getRealPath("/") will return you the current installation directory of your project.
And as #Kukeltje suggested, never ever save an uploaded file to your project directory, ... save it outside the webapps or even outside your container.
Therefore create a directory outsite your container (where you want to place your uploaded copies) and append ../ to the above path for each back step.
Say, if your application is deployed at D:/Tools/Tomcat7/webapps/your-application-name (e.g. on Windows using Tomcat) and you want to save copies to D:/Tools/uploads then following will give you required file path:
String uploadsFilePath = FacesContext.getCurrentInstance().getExternalContext()
.getRealPath("../../../uploads");
Use it with the Paths.get(uploadsFilePath) and develop your download logic (I am not sure which library you are using for the Paths class).
How about getClassLoader().getResource(Path/to/file)
So like
MyClass.class.getResource(bla/bla)
Which are now nested in src/resources
Like this You are system independent
#profit
You have several options:
For very quick development, you can use a hardcoded path, but be sure that it exists in your SUT (system under test).
You can define it as a static final string in your module, but this means that each time you want to change that path, you will need to recompile...
You can read that value from a property/config file.
There are more options (like using the registry if you are on Windows, or using an environment variable).

Best way to process command line file path argument in Java

I'd like to pass a file path argument to my application in a relative form, e.g ~/test.conf or ../test.conf, but i can't get a proper full file path, though i've tried it with old java.io and new java.nio Files/Paths. Is there a general way to get a resolved file path without large amount of code? It would be fine for the solution to work only in unix envs like OsX or Debian.
Update
With a provided argument like ~/test.conf
in case of getAbsolutePath it returns a path with a prefixed current folder - /Users/currentUser/Projects/Personal/TestProject/~/text.conf. Canonical path returns the same.
The hard bit here is dealing with POSIX home directories, and sure you deal with ~otheruser/dir/test.conf too (if you want to do it properly).
Luckily that's covered in How to handle ~ in file paths.
TL;DR - use something like:
path.replace("~/", System.getProperty("user.home") + "/");
Once you've done that, and as others have commented, you can just use standard java.io methods (including getCanonicalPath()).

Thread.currentThread().getContextClassLoader().getResourceAsStream() returns null

I have following code block in my application;
InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(FilePath);
Here 'FilePath' is an absolute path of the file.
Above code works fine in linux and in windows when i run the application in normal mode.(ie: in command prompt)
But this is NOT working, when I run the application as a windows service. I get input stream as 'null'.
Anyone encountered such issue before? I could not find any information regarding this other than java classloaders . Here we use "ContextClassLoader", which is the right classloader to be used..
Any clue on this?
I think this happens because you have "." (the current folder) on the classpath. That is a) a bad idea and b) makes your app break in odd ways.
What you need to understand is the difference between a file and a resource. A file is something outside of the classpath.
You should use File and FileReader to access them.
A resource is something on the classpath. Paths for resources always use / as file separator and not File.separator.
Another way to fix this is to add $HOME/repository/ (Linux) or %HOME%/repository/ to the classpath and load the resource using "resources/api_templates/api.xml". for this to work, resources must be a folder in $HOME/repository/.
If you don't do this, then all files in your home directory (or whatever directory you happen to start the application in) are added as resources to the classpath.

How to open file with default application in SWT?

I have for example .pdf file (path to that file). How to open this file in default application (probably Acrobat Reader) from SWT application (for example on Button click) ?
You should be able to use:
Program.launch(file);
to open the file (using the default application or creator). From the javadoc:
Launches the operating system executable associated with the file or URL (http:// or https://). If the file is an executable then the executable is launched. Note that a Display must already exist to guarantee that this method returns an appropriate result.
Note that there are some peculiarities in Program.launch() (or at least there were, though these may have been fixed in more recent versions of the runtime.) I don't really remember the specifics of the bugs, but we do some checks to work around some issues:
If you're on a Unix platform, and you're specifying an absolute path, there may be trouble opening that file. We prefix absolute paths with /. - so that /tmp/foo would be translated to /./tmp/foo - although I don't really remember the specifics of this bug any more than that.
On Windows, if you're trying to open a UNC path - for example \\server\bar - you need to wrap the string in double-quotes. For example: Program.open("\"\\server\bar\"");
Try Desktop.open:
Desktop.getDesktop().open(file);
Maybe this can help to find a decision: we ran into PermGen space trouble upon call Desktop.open() - which is in AWTpackage - out of our SWT application.
So I would prefer Program.launch() over Desktop.open() in a SWT-environment.

File paths in Java (Linux)

I have created a Java application that loads some configurations from a file conf.properties which is placed in src/ folder.
When I run this application on Windows, it works perfectly. However when I try to run it on Linux, it throws this error:
java.io.FileNotFoundException: src/conf.properties (No such file or directory)
If you've packaged your application to a jar file, which in turn contains the properties file, you should use the method below. This is the standard way when distributing Java-programs.
URL pUrl = this.getClass().getResource("/path/in/jar/to/file.properties");
Properties p = new Properties();
p.load(pUrl.openStream());
The / in the path points to the root directory in the jar file.
Instead of
String PROP_FILENAME="src/conf.properties";
use
String PROP_FILENAME="src" + File.separator + "conf.properties";
Check the API for more detail: http://java.sun.com/j2se/1.5.0/docs/api/java/io/File.html
I would also check what your current working directory is if your path to that file is relative. You just need to make a File test = new File("."); and then print that files canonical path name.
If you are referencing any other locations like user.dir or something to that effect by using System.getProperty(), you'll want to at least verify that the directory you are using as the relative root is where you think it is.
Also, as Myles noted, check the slashes used as file path separators. Although you can always use the "/" and it works.
And if you are referencing the path absolutely, you'll have trouble going between one OS and another if you do something silly like hard-code the locations.
What you want to do is check out System.getProperties() and look for file.separator. The static File.pathSeprator will also get you there.
This will allow you to build a path that is native for whatever system you're running on.
(If indeed that is the problem. Sometimes I like to get the current directory just to make sure the directory I think I'm running in is the directory I'm really running in.)
Check your permissions. If you (or rather, the user that the Java process is running under) doesn't have appropriate permissions to read the file, for example, you would get this error message.
This is a typical Windows -> Linux migration problem. What does ls -l src/conf.properties show when run from a prompt?
Additionally, check capitalisation. Windows isn't case-sensitive, so if the file was actually called e.g. CONF.properties it would still be found, whereas the two would be considered different files on Linux.
You should check the working directory of your application. Perhaps it is not the one you assume and that's why 'src' directory is not present.
An easy check for this is to try the absolute path (only for debugging!).
I would check your slashes, windows often uses '\' vs linux's '/' for file paths.
EDIT: Since your path looks fine, maybe file permissions or executing path of the app is different?
check your slashes and colons
in my case i set my PS1 to following value
PS1='\n[\e[1;32m]$SYSNAME(\u)#[\e[1;33m]\w [\e[1;36m](\d \T) [!]\e[0m]\n\$ '
i am trying to read from the env .such as system.getenv
Java was throwing exception
java.lang.IllegalArgumentException: Malformed \uxxxx encoding
Try the double slash, after doing things in JBoss I often had to refactor my code to use the double slashes

Categories

Resources