I'm trying to load an image file.
File imageCheck = new File("Users/me/Documents/workspace/ChineseChess/src/RCar.gif");
if (imageCheck.exists())
System.out.println("Image file found!");
else
System.out.println("Image file not found! :(");
button.setIcon(new ImageIcon("Users/me/Documents/workspace/ChineseChess/src/RCar.gif"));
Should I put RCar.gif in the src or bin folder of an eclipse project?
How would I refer to it without the explicit path? (I'm using a mac. I believe it should be something like ~/RCar.gif but am having trouble finding the correct syntax online.
Thanks!
If you want to use relative paths, they are going to be relative to the project's root, or when its deployed, the directory that the jar file resides in. You can use src/RCar.gif as your filename.
It would be better if you created a separate folder for resources, then address them with new File("res/RCar.gif"); Another option is to put them in the src folder and address them using the classloader.
If I recall correctly, Eclipse requires all resources to be placed in the resources directory. These will be automatically bundled with your application when you export it.
At runtime, you would simply use Class#getResource("/path/to/your/resource") where the path is the location from the "resource" folder
You can load the icon quite easily when it is in the resource folder of the class it belongs to at runtime.
See http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getResource%28java.lang.String%29
Within the class your.packagename.YourClassName you could write the following:
String folderName = YourClassName.class.getName().replace('.', '/' );
String urlString = "/"+folderName+"/RCar.gif";
URL fileUri = YourClassName.class.getResource(urlString);
button.setIcon(new ImageIcon(fileUri));
The urlString would be /your/packagename/YourClassName/RCar.gif. Of course this is also where icon should be at runtime.
HTH
yes...it takes the relative path.
public static final String FILE_PATH = "src/test/resources/car.png";
Related
I want to read a number of images which are on a folder called images at the same folder with my source code files. The path I use to read each image, is ..\images\imageX.jpg. But it does not recognize it. I am using Netbeans.
This will get you the path to the src/ directory in your web application:
String path = YourClass.class.getProtectionDomain().getCodeSource().getLocation().getPath();
You can then append anything you need to navigate to your images directory. So assuming that the images directory were located in a folder inside the src directory, the following should do the trick:
File imageFile = new File(path + "images/imageX.jpg");
Keep in mind that getPath() will return with a trailing forward slash at the end, so you don't need to include one when further resolving the path to your files.
Hey is it possible to get an image from file without using the full file location in java? My code below will only work with the full file path:
Icon icon = new ImageIcon("/Users/MyMac/Documents/Project/Software/Project/src/UI/Images/default_pic.png");
Is it possible to use the file path as such?:
Icon icon = new ImageIcon("/src/UI/Images/default_pic.png");
"/src/UI/Images/default_pic.png" is an absolute path, so it will look for a src directory in the root directory, then a UI subdirectory in it, etc. Not what you want.
You can use a relative path such as "src/UI/Images/default_pic.png" (notice it doesn't start with a "/"), but as its name says, it is relative to the current directory. So it will work if your current directory is /Users/MyMac/Documents/Project/Software/Project (or any directory that contains the file in the same subpath), otherwise it won't.
Finally, another way is to access the file through the classpath. Considering that the project could be packed in a jar file, the image file might not be a separate file on the disk, but you can still get a URL or InputStream to access it. Search for getResource and getResourceAsStream in Class and ClassLoader.
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 have a java application project in Netbeans. I have just one class.
I try to do this
FileReader fr = new FileReader("sal.html");
I have the file sal.html under the same package. But I get this error when I run:
Errorjava.io.FileNotFoundException: sal.html (The system cannot find the file specified)
My guess is that Netbeans is invoking the JVM from your project's root folder. Quoting a portion of the File Javadoc:
By default the classes in the java.io package always resolve relative pathnames against the current user directory. This directory is named by the system property user.dir, and is typically the directory in which the Java virtual machine was invoked.
To verify relative path resolution you could try:
System.out.println(System.getProperty("user.dir"));
System.out.println(new File("sal.html").getAbsolutePath());
You could then move your file to wherever java is looking for it. Most probably your project's root folder.
You could also consider using the class loader to read files as resources inside packages using getClass().getResourceAsStream("sal.html");. This is the preferred way of accessing resources since you no longer have to worry about absolute vs. relative paths. If a resource is in your classpath, you can access it. See this answer for more.
Put your file to main project folder. Not to any sub folders like src, or bin etc. Then it will detect your file.
Click on file view in Netbeans. Move sal.html to the project folder. Such that you will see it like this
- JavaProject
+ build
+ lib
+ nbproject
+ src
+ build.xml
manifest.mf
sal.html
Now
FileReader fr = new FileReader("sal.html");
will work.
System.out.println(System.getProperty("user.dir"));
System.out.println(new File("sal.html").getAbsolutePath());
Then it will show where the JVM is retrieving the files from. Usually for linux in the /home/username/NetbeansProjects/ApplicationName/.
Put your resources or files to this path
I think your problem is in the relative path to the file. Try to declare FileReader with full path to file.
FileNotFoundException means file not found.
The build folder for the netbeans is different where there is no file sal.html.
Try using absolute path in place of using relative path.
This is not a "File not found" problem.
This is because each class hold its own resources (let it be file, image etc.) which can be accessed only through a resource loader statement which is as below:
InputStream in = this.getClass().getResourceAsStream("sal.html");
The only fix is that you will get an InputStream instead of a file.
Hope this helps.
In my Java app I need to get some files and directories.
This is the program structure:
./main.java
./package1/guiclass.java
./package1/resources/resourcesloader.java
./package1/resources/repository/modules/ -> this is the dir I need to get
./package1/resources/repository/SSL-Key/cert.jks -> this is the file I need to get
guiclass loads the resourcesloader class which will load my resources (directory and file).
As to the file, I tried
resourcesloader.class.getClass().getResource("repository/SSL-Key/cert.jks").toString()
in order to get the real path, but this way does not work.
I have no idea which path to use for the directory.
I had problems with using the getClass().getResource("filename.txt") method.
Upon reading the Java docs instructions, if your resource is not in the same package as the class you are trying to access the resource from, then you have to give it relative path starting with '/'. The recommended strategy is to put your resource files under a "resources" folder in the root directory. So for example if you have the structure:
src/main/com/mycompany/myapp
then you can add a resources folder as recommended by maven in:
src/main/resources
furthermore you can add subfolders in the resources folder
src/main/resources/textfiles
and say that your file is called myfile.txt so you have
src/main/resources/textfiles/myfile.txt
Now here is where the stupid path problem comes in. Say you have a class in your com.mycompany.myapp package, and you want to access the myfile.txt file from your resource folder. Some say you need to give the:
"/main/resources/textfiles/myfile.txt" path
or
"/resources/textfiles/myfile.txt"
both of these are wrong. After I ran mvn clean compile, the files and folders are copied in the:
myapp/target/classes
folder. But the resources folder is not there, just the folders in the resources folder. So you have:
myapp/target/classes/textfiles/myfile.txt
myapp/target/classes/com/mycompany/myapp/*
so the correct path to give to the getClass().getResource("") method is:
"/textfiles/myfile.txt"
here it is:
getClass().getResource("/textfiles/myfile.txt")
This will no longer return null, but will return your class.
It is strange to me, that the "resources" folder is not copied as well, but only the subfolders and files directly in the "resources" folder. It would seem logical to me that the "resources" folder would also be found under `"myapp/target/classes"
Supply the path relative to the classloader, not the class you're getting the loader from. For instance:
resourcesloader.class.getClassLoader().getResource("package1/resources/repository/SSL-Key/cert.jks").toString();
In the hopes of providing additional information for those who don't pick this up as quickly as others, I'd like to provide my scenario as it has a slightly different setup. My project was setup with the following directory structure (using Eclipse):
Project/
src/ // application source code
org/
myproject/
MyClass.java
test/ // unit tests
res/ // resources
images/ // PNG images for icons
my-image.png
xml/ // XSD files for validating XML files with JAXB
my-schema.xsd
conf/ // default .conf file for Log4j
log4j.conf
lib/ // libraries added to build-path via project settings
I was having issues loading my resources from the res directory. I wanted all my resources separate from my source code (simply for managment/organization purposes). So, what I had to do was add the res directory to the build-path and then access the resource via:
static final ClassLoader loader = MyClass.class.getClassLoader();
// in some function
loader.getResource("images/my-image.png");
loader.getResource("xml/my-schema.xsd");
loader.getResource("conf/log4j.conf");
NOTE: The / is omitted from the beginning of the resource string because I am using ClassLoader.getResource(String) instead of Class.getResource(String).
When you use 'getResource' on a Class, a relative path is resolved based on the package the Class is in. When you use 'getResource' on a ClassLoader, a relative path is resolved based on the root folder.
If you use an absolute path, both 'getResource' methods will start at the root folder.
#GianCarlo:
You can try calling System property user.dir that will give you root of your java project and then do append this path to your relative path for example:
String root = System.getProperty("user.dir");
String filepath = "/path/to/yourfile.txt"; // in case of Windows: "\\path \\to\\yourfile.txt
String abspath = root+filepath;
// using above path read your file into byte []
File file = new File(abspath);
FileInputStream fis = new FileInputStream(file);
byte []filebytes = new byte[(int)file.length()];
fis.read(filebytes);
For those using eclipse + maven. Say you try to access the file images/pic.jpg in src/main/resources. Doing it this way :
ClassLoader loader = MyClass.class.getClassLoader();
File file = new File(loader.getResource("images/pic.jpg").getFile());
is perfectly correct, but may result in a null pointer exception. Seems like eclipse doesn't recognize the folders in the maven directory structure as source folders right away. By removing and the src/main/resources folder from the project's source folders list and putting it back (project>properties>java build path> source>remove/add Folder), I was able to solve this.
resourcesloader.class.getClass()
Can be broken down to:
Class<resourcesloader> clazz = resourceloader.class;
Class<Class> classClass = clazz.getClass();
Which means you're trying to load the resource using a bootstrap class.
Instead you probably want something like:
resourcesloader.class.getResource("repository/SSL-Key/cert.jks").toString()
If only javac warned about calling static methods on non-static contexts...
Doe the following work?
resourcesloader.class.getClass().getResource("/package1/resources/repository/SSL-Key/cert.jks")
Is there a reason you can't specify the full path including the package?
Going with the two answers as mentioned above. The first one
resourcesloader.class.getClassLoader().getResource("package1/resources/repository/SSL-Key/cert.jks").toString();
resourcesloader.class.getResource("repository/SSL-Key/cert.jks").toString()
Should be one and same thing?
In Order to obtain real path to the file you can try this:
URL fileUrl = Resourceloader.class.getResource("resources/repository/SSL-Key/cert.jks");
String pathToClass = fileUrl.getPath;
Resourceloader is classname here.
"resources/repository/SSL-Key/cert.jks" is relative path to the file. If you had your guiclass in ./package1/java with rest of folder structure remaining, you would take "../resources/repository/SSL-Key/cert.jks" as relative path because of rules defining relative path.
This way you can read your file with BufferedReader. DO NOT USE THE STRING to identify the path to the file, because if you have spaces or some characters from not english alphabet in your path, you will get problems and the file will not be found.
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(fileUrl.openStream()));
I made a small modification on #jonathan.cone's one liner ( by adding .getFile() ) to avoid null pointer exception, and setting the path to data directory. Here's what worked for me :
String realmID = new java.util.Scanner(new java.io.File(RandomDataGenerator.class.getClassLoader().getResource("data/aa-qa-id.csv").getFile().toString())).next();
Use this:
resourcesloader.class.getClassLoader().getResource("/path/to/file").**getPath();**
One of the stable way to work across all OS would be toget System.getProperty("user.dir")
String filePath = System.getProperty("user.dir") + "/path/to/file.extension";
Path path = Paths.get(filePath);
if (Files.exists(path)) {
return true;
}