Java - getting image from file path - java

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.

Related

Cannot Construct An Image Object With Relative File Path WIthout Using file: Prefix

I have been trying to create an image object like this:
Image img = new Image("images/jack.png");
or
Image img = new Image("jack.png");
or /jack.png or /images/jack.pngetc.
I have looked up the working directory using System.getProperty("user.dir") and it is indeed where I put my image file. When I use file: prefix, it does work, like so:
Image img = new Image("file:images/jack.png");
However, it is also supposed to work without using it. In the textbook it is done without file:. I've seen other codes that work without it.
At the end of a bunch of chained exceptions, it says:
Caused by: java.lang.IllegalArgumentException: Invalid URL or resource not found
I also tried to read source code from OpenJDK and I could figure anything out because many methods were native and from what I traced I didn't understand how it didn't work. Also, I can create files the same way, I just can't create images. For instance, this works:
File file = new File("fileName.txt");
What causes this problem, what should I do to fix it?
I'm using NetBeans, if that matters.
Note that System.getProperty("user.dir") does not return the working directory. It returns the user directory.
A path relative to the working directory can be specified using a relative file path in the File constructor. However it's bad practice to rely on the working directory. Starting the application from NetBeans results in the working directory being the project directory, but this is not the case, If started in a different way.
Images you need in your application should therefore be added to the jar.
In this case you can retrieve the image URL via Class.getResource(). (convert to String using toExternalForm().)
If you have a File that references a image file, you can use the File instance to get a URL:
File file = ...
String urlString = file.toURI().toURL().toExternalForm();
Those URLs can be used with the Image constructor.
Note that
File file = new File("fileName.txt");
does not create a file. It just represents a file path. This file may or may not exist. Simply invoking the File constructor does not create a new one.
File file = new File("name.txt");
creates a file somewhere. It doesn't read the existing file whereas
Image image = new Image("pathToImage.png");
tries to read the existing image. In order to be able to read an image stored somewhere you need either the absolute path, which requires the protocol (http, file, ftp etc.) or you put your image into the 'known' directory, like the resources dir of your project.
Say, you have your java sources under src/main/java. The resources dir could be src/main/resources. Put your image there and try working with relative path relative to src/main/resources.

How Can I Return the Executable's .java file path?

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.

File object not working in Java Web App

I have a simple java class in my web application in which i have written the below code but its not working
File test= new File("/templates/xmdForModel.xsd");
templates folder is inside the root folder of the application.
the location of the file is ----> application-root/package/test.java
location of the file is --------> application-root/testRoot/template/xmdForModel.xsd
Error
Failed to read schema document 'file:/templates/xmdForModel.xsd', because 1) could not find the document; 2) the document could not be read; 3) the root element of the document is not .
If you want to look up the file name for files inside of your web application, you can use ServletContext#getRealPath.
However, I would recommend loading your resources using the classloader with Class#getResourceAsStream. This way, it even works if the file does not really exist as a file (for example only inside of a jar).
If this is a file that a user is supposed to edit (or that you write to), I would place it outside of the web application, and then specify an absolute path (for example "/etc/myapp/conf/xmd.xsd") with a configurable prefix.
Path in the File constructor can be absolute or relative. When you start the path with '/' (in a linux based os), it is going to consider that path as an absolute path and create a file/folder in the root of your file structure (not in the root of the project). It will be like specifying c:\templates in windows machine.
Try removing the first slash and running your program. Removing first slash will make the part relative from your .java file. So you can use ../ to switch to parent folder.
java: application-root/package/test.java
file: application-root/testRoot/template/xmdForModel.xsd
So from your java file you will need to change directory to application root folder and then select template folder. Like following.
File x = new File("../testRoot/template/xmdForModel.xsd");
src:http://docs.oracle.com/javase/tutorial/essential/io/path.html
/home/sally/statusReport is an absolute path. All of the information
needed to locate the file is contained in the path string.
A relative path needs to be combined with another path in order to
access a file. For example, joe/foo is a relative path. Without more
information, a program cannot reliably locate the joe/foo directory in
the file system.

How to specify relative file path in Java file so that it can still work after the file is put in jar file?

Suppose I have a Java class that needs to access a file with absolute path
/home/gem/projects/bar/resources/test.csv:
package com.example
class Foo {
String filePath = ????? // path to test.csv
String lines = FileInputStream(new File(filePath).readAllLines();
}
Where the path to Foo.java is /home/gem/projects/bar/src/com/example.
Of course I cannot specify absolute path to the resource file. This is because jar file will be distributed as library for any clients to use in their own environments.
Assume the resource file like test.csv is always in the same path relative to project root. When a jar is created containing Foo.class, this jar also contains test.csv in the same relative path ( relative to project root).
What is the way to specify relative path that would work no matter where the project bar is moved to? Also how can I create a jar file (which can be in any location) so that the path to the resource file test.csv would still be correct.
To keep things simple, I have used invalid Java API ( readAllLines() which reads all the lines and return a string containing entire file content. Also not using try/catch).
Assume csv file can be read as well as written to.
I hope this makes it clear now.
Put the test.csv file into the src folder and use this:
Foo.class.getResourceAsStream("/test.csv")
To get an InputStream for the file. This will work wherever the project is moved, including packaged as a JAR file.
Example:
ProjectX\src\Test.java
ProjectX\resources\config.properties
If you have the above structure and you want to use your config.properties file, this is how you do it:
InputStream input = new FileInputStream("./resources/config.projects");
In this example you don't have to worry about packaging your source into jar file. You can still modify your resources folder anytime.
Use getResource(), as shown here.

Opening a local file in Groovy

I want to use a File object to read a local file in the same directory as a groovlet. However, using a relative path to the file (either "example.txt" or "./example.txt") doesn't do the trick. If I give it an absolute path (e.g., "/example.txt"), then it works.
Is there any way to get the working directory or context path of the groovlet programmatically?
new File("${request.getContextPath()}/example.txt")

Categories

Resources