Image path formatting - java

I'm trying to put an image to pdf file in my spring application. The code is
URL imageUrl = getClass().getResource(LOGO_PATH);
Image logo = Image.getInstance(imageUrl);
I have the image in source packages in com.application.pdf -package. How do I reference to LOGO_PATH then?
private static final String LOGO_PATH = "/src/java/com/application/pdf/logo.gif";
gives me null pointerexception.

You are tried to find resource in src folder, but in runtime you have to get resource from other folder, compile folder ( for example resource ) or from jar file, try to change your path to compile folder and I think all will be ok.
UPDATE
Could you provide structure of your application and I will help you to write correct path?

Related

when I use getInstance of itext for image it is redirecting to different location [duplicate]

I'm doing the letter generation with iText (pdf/rtf) in java servlet and got a problem with accessing images. The images are in the WebContent/images folder. When I run it in a local server and pointing the full path of images directory (c://eclipse/myproject/WebContent/images/letterHead.jpg) its working, but it fails running on the server with the directory ("WebContent/images/letterHead.jpg").
The project is being deployed as a WAR on a tomcat server, thus ending up with an address similar to
http://someserver:8081/projectName/someJSP.jsp
I don't understand how to reference the images relatively in this environment, and any help would be much appreciated.
Here is my code
Image imghead = Image.getInstance("WebContent/images/letterHead.jpg");
imghead.setAbsolutePosition(35,770);
imghead.scaleAbsolute(125, 42);
document.add(imghead);
You should never use relative paths in java.io stuff. You will be dependent on the current working directory which is in no way controllable in case of a webapplication. Always use absolute disk file system paths. Thus, c:/full/path/to/file.ext.
You can use ServletContext#getRealPath() to convert a relative web path to an absolute disk file system path. The relative web path is rooted on the public webcontent folder which is in your case thus /WebContent. So, you need to replace the first line of above code by:
String relativeWebPath = "/images/letterHead.jpg";
String absoluteDiskPath = getServletContext().getRealPath(relativeWebPath);
Image imghead = Image.getInstance(absoluteDiskPath);
// ...
Following piece of code may help you...
String path = request.getContextPath();
String split_path[] = path.split("/");
path = request.getRealPath(split_path[0]);
String imagePath="\\resources\\images\\letterHead.jpg";
Image image = Image.getInstance(path+imagePath);
Following code can be used to access image path inside a java class.
URL imageUrl = getClass().getProtectionDomain().getCodeSource().getLocation();
Image img=Image.getInstance(imageurl+"../../../some/images/pic.gif");
So I had the same problem, I wanted to add an image to the pdf but through a relative path, so when I made a executable program it would work in any computer, even if it had or not the image saved.
I found a way where you add the image as a resource of your application. You need to put the image inside the src directory or the dir of the class where you call it and then you can use the following code:
Image image = Image.getInstance(yourClassName.class.getResource("/yourImageName")));
If you put the image inside a folder then, obviously, you'll need to add the path through the folders name ("folderName/yourImageName"). Hope it helps!
For Kotlin, if the image is in the resources folder, you can also try the following:
Image.getInstance(this::class.java.classLoader.getResourceAsStream("images/your_image.png").readBytes())
Resources
Image foto = Image.getInstance(this.getClass().getResource("/static/img/gobierno.jpg"));

Java - How To Set An Image Path Without Using The C:\\ Direcory

I created a java app and I put some images in it and even gave it an image icon as the desktop image, but when i made it a jar file, and put it on another pc, all images were gone. This is the image path :
File imageFile = new File("C:\\Users\\Favour's Computer\\workspace\\Physics Calculator\\src\\res\\icon.jpg");
I checked it online and i found out that the problem is that i got the file through the C:\\ directory, they said the image file should look like this :
File imageFile = new File("res/icon.jpg");
I tried this but it didnt work, I kept getting an error message like : file not found
This is my full code :
BufferedImage image = null;
try {
File imageFile = new File("C:\\Users\\Favour's Computer\\workspace\\Physics Calculator\\src\\res\\icon.jpg");
image = ImageIO.read(imageFile);
} catch(IOException e) {
e.printStackTrace();
}
setIconImage(image);
Please, i have been trying to solve this for weeks, do anyone know how i can solve this, please if you do, please help
The images should not be loaded from the file system, but should be bundled into the app, inside your jar.
If you put the image foo.png inside the jar, under the package com.bar.resources for example, you simply need to use
InputStream in = getClass().getResourceAsStream("/com/bar/resources/foo.png")
to load the image as an input stream.
That will use the class loader to load the image. So, during development, if you're using a standard IDE project, you just need to put the image file in the appropriate package in your source directory: the IDE will "compile" the file by copying it to the same directory as the generated .class files.
If you're using a standard Maven/Gradle project, then it needs to be put in the appropriate package under src/main/resources.
Problem is you dont have res folder in your project, first of create a folder a "res" by Right Clicking on project and place the image icon.jpg image in that "res". and
use : `File imageFile = new File("res/icon.jpg");`// To retrieve image to your project.
You cannot retrieve the image from your local system, because it is not attached with your projects workspace.
There are two options....
1)Either make res a "source folder" . You will know this if you are using Eclipse.
Then you can use like
ImageIO.read(new File("res/icon.jpg"));
2) If res is a normal folder, you will have to use. In this case res will be considered as a package
ImageIO.read(new File("src/res/icon.jpg"));

Path for image file in Eclipse src folder, on a Mac

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";

Getting file path from file name located in a directory in java

I have some jasper reports file inside a directory called "reports" which is located 2-3 level at the bottom of the "src" package in eclipse IDE. How could get the related file paths inside "reports" folder. I don't want to get the paths like "C:\Users\Kara\workspace\MyProject\src\main\resources\reports\someFile.jrxml". I tried to get them by following code but it didn't give me the real path.
File testFile = new File("someFile.jrxml");
String absPath = testFile.getAbsolutePath();
If the reports are alway in your classpath (which they appear to be, assuming a standard Maven directory layout), use Class.getResource()/ClassLoader.getResource() to get a URL pointing to your report file. You can use this URL to extract the absolute path to your report file.
URL reportUrl = getClass().getResource("reports/someFile.jrxml");
You can try this:
URL url = getClass().getResource("/reports/someFile.jrxml");
url.getPath();

open resource with relative path in Java

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;
}

Categories

Resources