I'm self taught, and while trying to load an image with getClass().getResource(path) I think I've highlighted a problem with how I structure my projects. I currently just use cmd and TextPad.
My folder structure is as follows:
Desktop/Java/uk/co/woodward/recruit
/build
/images
/src
I compile from the Java folder in command prompt using
javac -d "." uk/co/woodward/recruit/src/example.java
The .java files are in package uk.co.woodward.recruit.build;
This all works fine and classes end up in the build folder, but while reading how to use icons in the java trail I realised that "build" isn't a package and I'm a little confused about how to set the location of an image file relative to the current class. I'm also unsure of whether I should set 'Java' (or recruit) as a root variable/path of some sort, rather than just compiling from there.
Anyway, nothing I've tried so far has worked.
public CandidateFormToolBar(){
saveButton.setIcon(createIcon("/images/save.png", "Save"));
add(saveButton);
}
private ImageIcon createIcon(String path, String btnName){
URL url = getClass().getResource(path);
if(url == null)
System.err.println("\nThe " + btnName + " Icon Path Cannot Be Found: " + path + "\n");
return new ImageIcon(url);
}
When running the program I've tried having the image in the build folder with the classes and using the path "save.png", I've tried the above code (which I thought would go up a level to the recruit folder and then to the image folder), with no luck. I've tried using -cp to point the jvm to the images folder. And much more.
And the outcome is that I've realised I still don't understand this well enough, and that my structure probably isn't recommended. Which is slightly depressing!
If anyone could point me vaguely in the right direction it would be appreciated!
Put your images inside the folder where you have put your Java files. Like in case of tomcat server this is the structure I use for accessing images in my jsp files.
>>Web content
>imagesfolder
>Web-inf
Myfile.jsp
Now in this Myfile.jsp file for accessing images from imagefolder I use following url "imagesfolder/myimage.png". Here Web content is the folder which have Myfile.jsp and 2 sub folder imagesfolder and web-inf and imagesfolder contains myimages.png
You can also make a directory like this if your file are in Java folder then create a image folder in that and access them using the url pattern mentioned above.
Hope this solve your query.
Related
I am creating an eclipse workspace starting by a java project (not written by me).
I am facing problems with the following method:
public static URL getURL(String fileName) {
URLClassLoader urlLoader = (URLClassLoader) getInstance().getClass()
.getClassLoader();
URL fileLocation = urlLoader.findResource(fileName);
return fileLocation;
since the findResource doesn't find the JPG resource (filename = "icons/INIT.JPG").
Looking on urlLoader.getUrl, I noticed the class aims only to jar files. Adding the folder icon to the Project->Libraries under eclipse I managed to let findResources look into the icon folder: nevertheless, the image is not a jar file and so it isn't considered.
Honestly, I don't get the point of using this process to load an image, but I cannot change the code and I was hoping in a solution within Eclipse project setup.
Thanks in advance
Based on the answers to my questions in the original comment, there are some facts:
You cannot change the code, and it looks like it's retrieving the AppClassLoader.
Even if you cast it into URLClassLoader, it's still an instance of an AppClassLoader, so it will look for the contents of the classpath and all JAR/ZIP files in JAVA_HOME\lib\ext.
You said that the project is guaranteed to work without to move the file anywhere, so there's only one option: add the file that you want to retrieve with the ClassLoader to the classpath.
Right click on the project, select Build Path and choose Configure Build Path.
Click on Source > Add Folder... and add the folder where the resources that you want to take are.
PD: If you add the folder as Class Folder in the Libraries tab, the JPG image won't be recognised by the AppClassLoader.
I made the following code to put in pictures to my java program:
private String ICET = "." + File.seperator + "Bilder/ICET.jpg"
//some code
label.setIcon(new ImageIcon(ICET));
//some code
It does, that the label has an IconImage and it works in every Workspace with a folder "Bilder", which is situated in the same folder as the program.
It works as a jar-file too, but if I convert the jar-file to an exe using launch4j, the program does not show the pictures.
use
new ImageIcon(getClass().getResource("path"));
path -> if is same folder put only name image : "ICET.jpg"
Most likely, the working directory set when started as an exe differs from when it is started as a jar-file, and thus your program looks at the wrong place for your "Bilder" folder.
You could try this out by printing the absolute path for it, e.g. like this:
System.out.println(new File(".").getAbsolutePath());
To fix the issue, you might try to set the chdir-option in the launch4j-config to . (a single dot). According to the docs:
<chdir>
Optional. Change current directory to an arbitrary path
relative to the executable. If you omit this property or leave it
blank it will have no effect. Setting it to . will change the current
dir to the same directory as the executable. .. will change it to the
parent directory, and so on.
But in the end, you should load the images from the class path, and not just from a folder. If you read them from the class path, they should hopefully be integrated into the exe, otherwise they are not and might get missing when users copy to exe to a new location, making your program no longer functioning.
I am trying to display an icon in my GUI by using a relative path, as in "display image from resources/image.png". I have tried a million different ways to express this, but nothing works. This makes me think it's a problem with my IntelliJ IDEA settings or project structure. I have set up the "resources" folder as a "resources folder". I don't know what else it expects me to do.
How can I load an icon from a file using a relative path in a Java project within IntelliJ IDEA?
My project structure:
src/main/java/ <-- set as "sources" in IntelliJ
src/main/java/ui/ <-- contains classes for my GUI
src/main/resources/ <-- set as "resources" in IntelliJ. Contains images.
Edit: Able to use relative path to confirm that file is found, not able to load it as icon.
String path = "src/main/resources/image.png";
System.out.println(new File(path).exists()); <-- true
I've encountered this issue many times and what worked for me was using InputStream
InputStream is = Main.class.getClassLoader().getResourceAsStream("name_of_file.png");
Using InputStream will allow you read from various file types. Now to load in the icon you can do
Icon icon = new ImageIcon(ImageIO.read(is));
Resources are on classpath, not on filesystem path - which is taken relative from running directory, which is project directory when you are running it from idea. Usually you will distribute your aplication as jar, and this it is better to load resources from classpath. In zour case - from root directory
I have a single image file in a folder in my Eclipse project that stores a image file (logo.jpg). However I don't know how to access it in my main program.
I had tried the following
private static URL logoPath
public class MainApplication
{
public void createGui()
{
logoPath.getClass().getResource("/Resources/images/logo.jpg");
////
}
/////
}
Problem is I keep getting a null pointer exception so obviously that path is done wrong or else the logoPath.getClass() is tripping it up.
Any ideas?
U can use this way
I have following package structure
src/test (package test contain Java files)
src/images (folder images contain images)
I am going to get image from
src/images/login.png at src/test/*.java
JLabel label = new JLabel(new ImageIcon(getClass().getResource("/images/login.png")));
You need to place your resources in a java source directory for them to be visible. You have two options:
Move your "resources" folder under your existing "src" folder.
Create a new source folder just for resources. You can do that in Java Build Path page of project properties.
Several things to watch out for...
Pay attention to your capitalization. Java resource lookup is case sensitive.
The path that you would use will be relative to the source folder (not project root). For instance, if you make your resources folder a source folder, your path will need to be "images/...". If you want to preserve resources folder in the lookup path, you will need to create an extra folder level in your project to serve as the source root for resources.
I am not certain whether it is an actual problem, but resources paths should not start with a leading slash. They aren't really paths in a traditional sense. Think of them as package-qualified class names, but with '/' instead of '.' as the separator.
I am doing that the same way
String filename = "logo.jpg";
Main.getClass().getClassLoader().getResource(filename);
And the file structure looks like this
/src/main/java/com/hauke/Main.java
/resource/logo.jpg
My problem was before that I named the direcotry "resources" and it should be "resource"
I need to read a text file when I start my program. I'm using eclipse and started a new java project. In my project folder I got the "src" folder and the standard "JRE System Library" + staedteliste.txt... I just don't know where to put the text file. I literally tried every folder I could think off....I cannot use a "hard coded" path because the text file needs to be included with my app...
I use the following code to read the file, but I get this error:
Error:java.io.FileNotFoundException:staedteliste.txt(No such file or directory)
public class Test {
ArrayList<String[]> values;
public static void main(String[] args) {
// TODO Auto-generated method stub
URL url = Test.class.getClassLoader().getResource("src/mjb/staedteliste.txt");
System.out.println(url.getPath()); // I get a nullpointerexception here!
loadList();
}
public static void loadList() {
BufferedReader reader;
String zeile = null;
try {
reader = new BufferedReader(new FileReader("src/mjb/staedteliste.txt"));
zeile = reader.readLine();
ArrayList<String[]> values = new ArrayList<String[]>();
while (zeile != null) {
values.add(zeile.split(";"));
zeile = reader.readLine();
}
System.out.println(values.size());
System.out.println(zeile);
} catch (IOException e) {
System.err.println("Error :"+e);
}
}
}
Ask first yourself: Is your file an internal component of your application?
(That usually implies that it's packed inside your JAR, or WAR if it is a web-app; typically, it's some configuration file or static resource, read-only).
If the answer is yes, you don't want to specify an absolute path for the file. But you neither want to access it with a relative path (as your example), because Java assumes that path is relative to the "current directory". Usually the preferred way for this scenario is to load it relatively from the classpath.
Java provides you the classLoader.getResource() method for doing this. And Eclipse (in the normal setup) assumes src/ is to be in the root of your classpath, so that, after compiling, it copies everything to your output directory ( bin/ ), the java files in compiled form ( .class ), the rest as is.
So, for example, if you place your file in src/Files/myfile.txt, it will be copied at compile time to bin/Files/myfile.txt ; and, at runtime, bin/ will be in (the root of) your classpath. So, by calling getResource("/Files/myfile.txt") (in some of its variants) you will be able to read it.
Edited: Further, if your file is conceptually tied to a java class (eg, some com.example.MyClass has a MyClass.cfg associated configuration file), you can use the getResource() method from the class and use a (resource) relative path: MyClass.getResource("MyClass.cfg"). The file then will be searched in the classpath, but with the class package pre-appended. So that, in this scenario, you'll typically place your MyClass.cfg and MyClass.java files in the same directory.
One path to take is to
Add the file you're working with to the classpath
Use the resource loader to locate the file:
URL url = Test.class.getClassLoader().getResource("myfile.txt");
System.out.println(url.getPath());
...
Open it
Suppose you have a project called "TestProject" on Eclipse and your workspace folder is located at E:/eclipse/workspace. When you build an Eclipse project, your classpath is then e:/eclipse/workspace/TestProject. When you try to read "staedteliste.txt", you're trying to access the file at e:/eclipse/workspace/TestProject/staedteliste.txt.
If you want to have a separate folder for your project, then create the Files folder under TestProject and then access the file with (the relative path) /Files/staedteliste.txt. If you put the file under the src folder, then you have to access it using /src/staedteliste.txt. A Files folder inside the src folder would be /src/Files/staedteliste.txt
Instead of using the the relative path you can use the absolute one by adding e:/eclipse/workspace/ at the beginning, but using the relative path is better because you can move the project without worrying about refactoring as long as the project folder structure is the same.
Just create a folder Files under src and put your file there.
This will look like src/Files/myFile.txt
Note:
In your code you need to specify like this Files/myFile.txt
e.g.
getResource("Files/myFile.txt");
So when you build your project and run the .jar file this should be able to work.
Depending on your Java class package name, you're probably 4 or 5 levels down the directory structure.
If your Java class package is, for example, com.stackoverflow.project, then your class is located at src/com/stackoverflow/project.
You can either move up the directory structure with multiple ../, or you can move the text file to the same package as your class. It would be easier to move the text file.
MJB
Please try this
In eclipse "Right click" on the text file u wanna use,
see and copy the complete path stored in HDD like (if in UNIX "/home/sjaisawal/Space-11.4-template/provisioning/devenv/Test/src/testpath/testfile.txt")
put this complete path and try.
if it works then class-path issue else GOK :)
If this is a simple project, you should be able to drag the txt file right into the project folder. Specifically, the "project folder" would be the highest level folder. I tried to do this (for a homework project that I'm doing) by putting the txt file in the src folder, but that didn't work. But finally I figured out to put it in the project file.
A good tutorial for this is http://www.vogella.com/articles/JavaIO/article.html. I used this as an intro to i/o and it helped.
Take a look at this video
All what you have to do is to select your file (assuming it's same simple form of txt file), then drag it to the project in Eclipse and then drop it there. Choose Copy instead of Link as it's more flexible. That's it - I just tried that.
You should probably take a look at the various flavours of getResource in the ClassLoader class: https://docs.oracle.com/javase/1.5.0/docs/api/java/lang/ClassLoader.html.