I've been having problems exporting my java project to a jar (from Eclipse). There is a file that I've included in the jar named images. It contains all of the image files used by my project. The problem is, my references to those images only work when the project isn't in jar form. I can't figure out why and I'm wondering if I need to change the wording of the image references. This is what I'm doing to reference images:
URL treeURL = null;
Image tree = null;
File pathToTheTree = new File("images/tree.png");
try {
treeURL = pathToTheTree.toURL();
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
tree = ImageIO.read(treeURL);
} catch(IOException e) {
e.printStackTrace();
}
Most likely it is a simple problem, as I'm a beginner at coding. What do I need to change to make these references work when it's all in a jar?
It is indeed simple: you use the various getResource() methods in java.lang.Class and java.lang.ClassLoader. For example, in your app, you could just write
treeURL = getClass().getResource("/images/tree.png");
This would find the file in an images directory at the root of the jar file. The nice thing about the getResource() methods is that they work whether the files are in a jar or not -- if the images directory is a real directory on disk, this will still work (as long as the parent of images is part of your class path.)
Related
In my project, I have created a package that am calling htmlRepository. In this package, I have created an Html file called mapping.html. I would like to access this file, convert it to a url so I can use the setPage method to diplay it in a JEditorPan.How can I access this file in order to get its url.
I have used the code below to do this if the file resides outside the project package i.e on some folder on my computer.
NodeName = Node;
try {
NodeURL = new File(filename).toURI().toURL();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
However, this means that when I create the jar then I will have to have another folder with the HTML.So I created the Html package so I can carry the Html files in the jar and access them from there. How can I go about this. Thank you in advance.
You should load it as a resource file using the context class loader as so:
URL url = Thread.currentThread().getContextClassLoader().getResource(fileName);
and by filename you should include the full nested directories before your file starting from the resources dir
I create a dynamic web app project using JSP/Servlet with eclipse. And I want to create a copy of "db.xls" file in the same place.
I try to create a copy of the "db.xls", the copy will named out.xls but it won't. These files should be located inside the same folder "files". My code compile, db.xls is correctly read, but file out.xls is not created.
What's wrong with my method ? Please help !
public void readExcel()
{
try{
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
URL url1 = classLoader.getResource("");
// read db.xls
wbook = Workbook.getWorkbook(new File(url1.getPath()+"/db.xls"));
// create a copy of db.xls nammed out.xls
wwbCopy = Workbook.createWorkbook(new File(url1.getPath()+"/out.xls"), wbook);
shSheet = wwbCopy.getSheet(0);
}
catch(Exception e)
{
e.printStackTrace();
}
}
I move the file "db.xls" inside WEB-INF and use getServletContext().getRealPath("/WEB-INF") but the output file "out.xls" still not created.
public void readExcel()
{
try{
// ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
// URL url1 = classLoader.getResource("");
String tomcatRoot = getServletContext().getRealPath("/WEB-INF");
wbook = Workbook.getWorkbook(new File(tomcatRoot+"/db.xls"));
wwbCopy = Workbook.createWorkbook(new File(tomcatRoot+"/out.xls"), wbook);
shSheet = wwbCopy.getSheet(0);
}
catch(Exception e)
{
e.printStackTrace();
}
}
System.out your files and you'll see what's wrong
System.out.println(new File(tomcatRoot+"/db.xls").getAbsolutePath());
System.out.println(new File(tomcatRoot+"/out.xls").getAbsolutePath());
You expect the file to be you project directory but it isnt read/writen from/to that location because you have set up the files forlder as source folder in eclipse, so it is part our yours assempbly and lands in the classpath where you can read from a resource, i.e. using classloader and getResource / getResourceAsStream but you cannot and should not write to it, for several resons, most obvious is that your web app might not be unpacked from a war files.
In fact, you dont know where you are reading/writing your files to/from.
You might package your file with the war file and read from it, this is correct. But for writing the best is to have an explicite location on the filesystem where you can write your output files. check this answer for how you could go abut it using context init parameter
check the WEB-INF/classes folder, it might be in there
I think your missing write and close statements.
Try:
wwbCopy.write();
wwbCopy.close();
In order to read files within a web application, the files need to be stored somewhere under the WEB-INF folder, otherwise they won't be deployed as part of the application.
Once you've moved the folders into there you can use the following method within a servlet:
String tomcatRoot = getServletContext().getRealPath("/");
This will give you the root of the web application. Then you must build the path (including the WEB-INF folder) from there:
String sourceFile = tomcatRoot + "/WEB-INF/folder/source.file"
String targetFile = tomcatRoot + "/WEB-INF/folder/target.file"
EDIT: I originally stated that getRealPath() would give you the WEB-INF location. It doesn't, it gives the parent folder.
I have a level editor thingy, and when i run it in eclipse everything is working as it should and everything shows up. I tried to export it both as a runnable jar and just a jar. None of them seemed to work. The problem is that the images, buttons and menus don't show up when i run the jar. I think it has something to do with resources.
Thanks in advance.
Edit:
I am using this function when loading images:
public static BufferedImage loadTileImg(String fn) {
BufferedImage img = null;
File file = new File(fn);
try {
img = ImageIO.read(file);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return img;
}
and i am using a URL to load icons.
How are you managing the resources?
Take care about full paths when you are showing it and exporting the resources properly.
Try with fat jar. Check the existence of the images and icon files in the exported jar.
Check the relative paths used for resources inside your code.
Hi i have exported my java project as executable jar file. inside my project I am accessing a Excel file containing some data. Now I am not able to access the Excel file when I am trying to access the file.
My project structure is:
Java_Project_Folder
- src_Folder
- resources_Folder(Containing excel file)
I am accessing the excel file like
FileInputStream file=new FileInputStream(new File(System.getProperty("user.dir")
+File.separator+"resources"+File.separator+"Excel.xlsx"));
I have tried accessing this file using getResourceAsStream like:
FileInputStream file=(FileInputStream) this.getClass().getResourceAsStream
("/resources/Excel.xlsx");
But i am getting in is null exception. whats wrong can anyone help?
I bet you have no package called resources in your project.
Trying to use Class.#getResourceAsStream is the way to go. But this method does not return a FileInputStream. It returns an InputStream wich is an interface.
You should be passing the absolute name of the resource
InputStream is = getClass().getResourceAsStream("my/pack/age/Excel.xlsx");
where the excel file is located in the directory
resources/my/pack/age
The first step is to include the excel file itself in your project. You can create a resources folder like you show, but to make sure this gets included in your jar, you add the resources folder in along with your source code files so that it gets built into the jar.
Then
InputStream excelContent = this.getClass().getResourceAsStream("/resources/Excel.xlsx");
should work. From one post at least, the leading forward slash may also mess things up if you use the ClassLoader.
getClass().getResourceAsStream("/a/b/c.xml") ==> a/b/c.xml
getClass().getResourceAsStream("a/b/c.xml") ==> com/example/a/b/c.xml
getClass().getClassLoader().getResourceAsStream("a/b/c.xml") ==> a/b/c.xml
getClass().getClassLoader().getResourceAsStream("/a/b/c.xml") ==> Incorrect
ref: getResourceAsStream fails under new environment?
Also in eclipse you can set the resources folder as a source folder like this:
in the properties of your eclipse project, go to java build path, select sources, and check to see if all needed source fodlers are added (as source folders). If some are missing, just add them manually using add sources... button
ref: Java Resources Folder Error In Eclipse
I tried this and it is working for me.
My Test1 class is in default package, just check where your accessing class is in any package, if it is then go back to exact resource folder from classpath like this "../"
public class Test1 {
public static void main(String[] args) {
new Test1();
}
Test1(){
BufferedInputStream file= (BufferedInputStream) this.getClass().getResourceAsStream("resources/a.txt");
try {
System.out.println((char)file.read());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
FileInputStream file= (FileInputStream)
this.getClass().getResourceAsStream("/resources/Excel.xlsx");
Why do you need FileInputStream? Use
InputStream is = getClass().getResourceAsStream..
Secondly use "resources/Excel.xlsx"
Thirdly when constructing file like this
new
File(System.getProperty("user.dir")+File.separator+"resources"+File.separator+"Excel.xlsx"));
is hard to control slashes. use
new File("parent (userdir property)", "child (resources\Excel.xlsx)")
I am using the eclipse IDE and I just exported my project using 'export->Runnable Jar'. In my code, I have loaded a map using
URL map1url = this.getClass().getResource("map01.txt");
and later
inputmap = new File(map1url.getFile());
and then scanned its data using
Scanner sc = null;
try {
sc = new Scanner(inputmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Now, when I package the map01.txt into the jar, and double click it, it runs, but can't find the map01.txt. When I use java -jar, it runs, but still can't find the map.
When I place map01.txt in the same directory as the jar file, but not actually in the jar, and then double-click it, it runs, but doesn't find the map. If I run it using java -jar it runs and loads the map. What is the cause of this problem? How can I fix it? And the map01.txt is the only resource that doesn't work. I have loaded many images that are placed into the jar file, and they all load and display fine. For the images I use
URL url = this.getClass().getResource("myImage.gif");
try {
BufferedImage myImage = ImageIO.read(url);
} catch (IOException e) {
}
Why do they work and not my map? How can I fix this so I can package ALL my resources into one jar and then double-click it to run?
When you say "new File(map1url.getFile())", you're ending up with a java.io.File that refers to a file in the current directory. If the file actually is in the current directory of the process (which will happen if the file in in the current directory of your shell and you use "java -jar", then this will work; otherwise, it won't.
Why not just use getResource().openStream() to read the map file?