How can I find image file within my Tomcat 8 java app? - java

In my Java tomcat application, I'm facing problems trying to get the correct file path.
Two code snippets from my Java app I need:
try {
InputStream in = getClass().getResourceAsStream("StaticContent/images/image.png");
image = ImageIO.read(in);
} catch (Exception e) {
System.out.print(e.getStackTrace());
}
Second snippet:
DataSource fds_image = new FileDataSource
("StaticContent/images/image.png");
I have put the image into the folder:
src/main/webapp/StaticContent/images/image.png
Folder structure
I have tried several ways to make sure the file path is correct, but nothing worked. Also, I put the image into the ressources folder and tried different paths but to no avail.
I assume that I choose the wrong (relative) path, but I don't know how to handle it.
Can anybody help me with this?

Related

How to create correct resource file path in a java jar file

Sitting here with a bigger java project (for a first year software student) having some troubles creating the correct file path to resources.
I right now have files in the form of .txt, .png, .jpg, and a .gif.
Right now i use paths like this to find a text file:
File userFile = new File("Source Code/files/users.txt");
Or paths like this to create an image loaded in my FX code:
File logoPath = new File("Source code/files/graphics/Streamy_logo.png");
Image logoImage = new Image(logoPath.toURI().toString());
logo.setImage(logoImage);
This works fine in my IDE (IntelliJ), however it doesn't work when i create the project as a Jar file.
I think is has to do with the "source code" directory not created in the jar-file, which makes sense now.
Tried to read different subjects, but it seems a bit different if i should use a getResources-method, set a resourceStream or something else.
Can anybody please help me with this.
Thank you!
You can't load files like that in .jar files here's an example on how to read BufferedImages.
But first, make sure you have marked the resource folder as a resource folder in IntelliJ by right-clicking the folder in the project view and going down to "Mark directory as" and checking resource root.
BufferedImage exampleBlock = null;
try {
exampleBlock = ImageIO.read(ClassLoader.getSystemResource("exampleBlock.png"));
} catch (IOException e) {
e.printStackTrace();
}
By using this method of getting files all your files will be implemented into the .jar file and you can use them by calling their file name + extension
For maven or gradle projects, that respects maven directories convention you can simply use
getClass().getResource("/your_file_located_in_src_main_resources.extension").getPath()

Illegal Argument Exception: URI is not hierarchical with runable .jar file

I know this question has been asked a bunch of times before, but I'm peeled through all the other threads and tried a bunch of stuff, but can't find anything that resolves my issue. I have a program that compiles and runs without issue in Eclipse, but when I export a runnable .jar file, it won't launch. I tried running it from the cmd prompt, and got the error Illegal Argument Exception: URI in not hierarchical. This is happening in an included sound file which I have as a classpath resource. The code is like this:
try {
pop = new File(IntroView.class.getResource("/model/pop.wav")
.toURI());
} catch (URISyntaxException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
From what I've read it's a problem with the way that the file is being packed up into the .jar, but I'm having a hard time wrapping my head around it. Can anybody shed some light on this and possibly provide a solution? Thanks.
I am sorry but it seems you cannot represent a File object from inside a JAR. When locating a file using File object it checks for file in the OS directory structure only. The File object can locate the JAR itself in a directory but not what's inside.
You can get the InputStream to the file inside JAR like this as stated in a few places:
InputStream input = PlaySound.class.getResourceAsStream("Kalimba.mp3");
You could have these options:
Read the file from JAR and write it outside in your directory and
then get the File Object.
Extract the JAR to a folder and point to that with a File.
Simply get the InputStream and play the file as shown here:
How can I play sound in Java?
Alright so I got it working, but it's not really an ideal solution. What I ended up doing is creating a folder within the project, but outside of the source. So before, the resources were in
Project/src/Model/pop.wav
Now they are in
Project/Resources/pop.wav
I then just accessed then like this
pop = new File("Resources/pop.wav");
So as this stands, it still only works when launching from the IDE, but what I did was add a new folder within the same folder that the .jar is being run from which contained all the same resource files. The file reference looks for pop.wav relative to whichever directory the program(either in the IDE of from the .jar) is being run from, so it finds the files in this new folder and works fine. I don't feel it's the prettiest solution, but it works anyway.

Displaying images within a jar file

I know this question has been asked before, but I have gone over all the solutions I could find and cannot make any of them work for me. I have a program in Eclipse that I am trying to export to an executable jar file. It is the first time I have done this. When I execute the jar, my program images do not show up. So I did some research and found I need to load them as resources, but I cannot seem to make it work.
Here is the code I was using to load the images without the jar:
private void initComponents()
{
// create an enterprise icon and make it invisible
enterpriseIcon = new JLabel(new ImageIcon("res/enterprise1.png"));
enterpriseIcon.setVisible(false);
}
I have all my images in a folder named res in my root project directory, and I told Eclipse to put this folder in the build path.
When the images wouldn't show up when running the jar file, I tried the following:
enterpriseIcon = new JLabel(new ImageIcon(getClass().getResource("/res/enterprise1.png")));
and
enterpriseIcon = new JLabel(new ImageIcon(Toolkit.getDefaultToolkit().getImage(getClass().getResource("/res/enterprise.png"))));
However, when either of these is run from within Eclipse, I get a null pointer exception. (I tried a few other things as well, but the above were the only solutions I thought I understood.)
Any help getting this to work would be appreciated.
Use Class#getResource to get the URL of your image inside the jar file
enterpriseIcon = new JLabel(new ImageIcon(getClass().getResource("/res/enterprise1.png")));
Try this. This works well for me :)
private void initComponents() {
try {
BufferedImage icon = ImageIO.read(getClass().getResource("/enterprise1.png"));
frame.setIconImage(icon);
} catch (IOException e) {
e.printStackTrace();
}
}
I was also facing the same issue till yesterday. I have got a fix for this. Let me share it with you.
In your Eclipse, go to your Project name.
Right your project name.
New -> Source file/folder
Name this Source file/folder as images
Now on your local machine go to the Eclipse workspace where your project
is physically present.
Copy ALL your images into the newly created
'images' folder right there only.
Now go back to Eclipse.
Right click on your Project -> Refresh
Now, wherever you are using images in your .java files , go to those lines and prefix the image location with images/
Example : XXX xxx = XXXX (example.jpg)
Change it with .... XXX xxx = XXXX (images/example.jpg)
BOOM !!
The images will be shown when you run the .jar file.
NOTE : Do not run the .jar file from cmd using java -jar AppName.jar
Instead, just double click the .jar file and you will be seeing the images.
If it works for you, kindly upvote. :)

How to use a .properties file in Eclipse Java Dynamic Web Project?

I'm developing a Dynamic Web Project in Eclipse. I created a .properties file for store database details (Username, Password etc.). I added it by right clicking on the project and New -> File . I used the Java util package Properties class. But it does not working. I can not retrieve any property from the file. Here is the code I used,
Properties prop = new Properties();
try {
prop.load(new FileInputStream("database.properties"));
String db = prop.getProperty("database");
String userName = prop.getProperty("dbuser");
String password = prop.getProperty("dbpassword");
} catch (IOException ex) {
ex.printStackTrace();
}
Is there something wrong or Is there any particular place where I should put properties file.
What you did is correct, ie right clicking the project and new--file.You have to Put your properties where you start your jvm from. Please look into the attached image. The properties file is marked in red. Look if your properties file is also located something like this.
Also add this in your code to find out where to put your file:
System.out.println(new File(".").getAbsolutePath());
For more details please follow this link- FileNotFoundException when using java properties file
Normally, you make sure the properties file is in the project runtime classpath (e.g. WEB-INF/classes) and then load it using either the System classloader or the property file handler's classloader, i.e. (Freehand typing from memory -- NOT COMPILED)
try{
Properties p = new Properties();
InputStream in = MyPropertyHandler.getClass()
.getClassLoader()
.getResourceAsStream("com/package/props/database.properties");
p.load(in);
catch(IOException e){
e.printStackTrace(System.err);
}
I'm betting you aren't pointing at the correct location. Make sure you're properties file is in the correct place. Using that code, I believe it is looking for ${CURRENT_WORKING_DIR}/database.properties, which is the case of a web app in eclipse is WEB-INF/classes (i think).
You should instead be using the more portable java.util.Properties#load(InputStream) with the result of javax.servlet.ServletContext#getResourceAsStream(String).
Try to give absolute path or relative path to the proprty file, also check this propery file path has been add to source folders or not, if not it will not be copied to your classes folder. (Right cclick on project , check java build path under source tab.
You should have .properties file in same package as class that is using it.
Or better, read properties file with getResourceAsStream method (otherwise you can have some problem later when you'll have file in .war archive).
InputStream inputStream =
getClass().getClassLoader().getResourceAsStream("database.properties");

how to open a pdf file from java?

I want to open a PDF file from a jsp. The jsp and the PDF are in the same directory.
I am using the following piece of code:
if (Desktop.isSupported()) {
try {
File myFile = new File("<file name>.pdf");
Desktop.getDesktop().open(myFile);
} catch (IOException ex) {
// no application registered for PDFs
}
}
However, I get the error that the file is not found.
Verified user.dir and it points to my tomcat/bin.
How can I refer to the pdf to open it?
You need to specify the absolute file path. Assuming that there's a filename.pdf in the root of the public webcontent, this should do:
File myFile = new File(getServletContext().getRealPath("/filename.pdf"));
However, this construct won't work the way you'd expect. It will show the PDF file in webserver machine, not in webbrowser machine! Only when you happen to run both the webserver and webbrowser at physically the same machine, this will "work". But this does obviously not happen in real world when you publish your webapp into the internet where the webserver and webbrowser runs at physically different machines.
Instead, you just need to link to the PDF file directly.
View PDF
and let the browser handle the display.
Have you tried this? I just got this from google, so I dunno if it will work.
Process p = Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler c:\\Java- Interview.pdf");
p.waitFor();

Categories