java get url of html file that is in project package - java

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

Related

Get absolute path of resource file inside a jar

I want to access a file inside a resource folder of the current jar running.
The file is inside of My_app.jar where is located to /apps/dashboard/
I tried to access it like this
String customScriptPath = "script/template.sh";
public String getTemplatePath() {
Resource temp= new ClassPathResource(this.customScriptPath, this.getClass().getClassLoader());
try {
File templateFile = temp.getFile();
logger.info("Script template path = "+templateFile.getAbsolutePath());
return templateFile.getAbsolutePath();
} catch (IOException e) {
logger.error(e.getMessage());
e.printStackTrace();
}
return null;
}
and I got this error
class path resource [script/template.sh] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/apps/dashboard/My_app.jar!/BOOT-INF/classes!/script/template.sh
You can't use File to access the template.sh. File is used to reference files in the file system. In your case, you are trying to reference something inside a jar file.
If you want to read content of template.sh, take a stream using Resource.getInputStream(). If you want to log location of the file, use Resource.getURL().

Loading resources from another maven module with mvn exec:java doesn't work

I have a maven project with this structure:
parent
-----module1
--------src
------------main
-----------------java
----------------------Loader.java
-----------------resources
-------------------------file1.txt
-----module2
--------src
------------main
-----------------java
-------------------------CallLoader.java
So Loader.java, loads files1.txt. I call this class from CallLoader.java from module2. This is the code I used
In Loader.java,
private static File getResourceFile(String fileName){
try {
URL resource = GraphUtil.class.getClassLoader().getResource(fileName);
return new File(resource.getPath());
} catch (Throwable e) {
throw new RuntimeException("Couldn't load resource: "+fileName, e);
}
}
where fileName="file1.txt".
I get an error because the file absolute path looks like this:
file:/home/moha/.m2/repository/my/package/name/%7Bproject.version%7D/base-%7Bproject.version%7D.jar!/file1.txt
What exactly am I doing wrong?
Get the content of your file as a stream instead in order to be able to read your resource from a jar file which is the root cause of your issue. In other words use getResourceAsStream instead of getResource.
You can also return the URL instead of File then call openStream() later to read it if needed.
NB1: the URL will be of type jar:file/... which cannot be managed by the class File
NB2: To convert a URL into a File, the correct code is new File(resource.toURI())

read/copy file inside dynamic web project in java

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.

Java: Can't read a file in my project directory?

I'm building a Vaadin(basically Java that compiles to html/javascript) project and am trying to import a template(basically a HTML file). For all intents and purposes thought, I'm just importing a file as an input stream. Here is the offending code:
File file = new File("C:/JavaProjects/VaadinSpikeWorkspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/CISTVaadinClient/VAADIN/themes/layoutsinteractionDetailsTabLayout.html");
InputStream is = null;
CustomLayout custom = null;
try {
is = new FileInputStream(file);
} catch (FileNotFoundException e1) {
System.out.println("mark 1");
e.printStackTrace();
}
try {
custom = new CustomLayout(is);
} catch (IOException e) {
System.out.println("mark 2");
e.printStackTrace();
}
What I'm doing:
Deploying the Vaadin project (basically a dynamic web project with a few extra .jars) to tomcat and accessing thVe aadin Project using my browser
What I'm seeing:
A blank screen in my browser
File not found exception (i.e "mark 1")
And as a result: IOException (i.e. "Mark 2")
What I've checked:
The file definitely does deploy to tomcat with the rest of the project
Outside of the webapps folder, the file i'm trying to import is available via the browser once deployed (i.e. Localhost/myProject/MyFile.html)
The Tomcat install is fine (It was a fresh install and works with this/other projects outside of this problem)
What I've tried
Using a relative URL, or just the name of the file (i.e. New File( "../webapps/vaadin/layouts/MyFile.html") )
Using the absolute Path to the Project directory
Using the absolute path to the deploy directory (as above)
Putting the file somewhere else (read: Every single possible location in the project)
Again, I'm trying to simply read the file, MyFile.html as an input stream. What am I doing wrong/ overlooking?
Thanks for your time.
I had no problems reading files when using VaadinService which points to WebContent directory (with META-INF, VAADIN and WEB-INF inside). If it's run in the test environment then VaadinService is not available, so I use such piece of code:
private static final String BASEDIR;
static {
if (VaadinService.getCurrent() != null) {
BASEDIR = VaadinService.getCurrent().getBaseDirectory().getAbsolutePath();
} else {
BASEDIR = "WebContent";
}
}
then to navigate to VAADIN folder just use
BASEDIR+="/VAADIN/restOfYourPath"
Just in order to make it more portable: have you thought about bringing your templates into your classpath? Something like
yourApp/WEB-INF/classes/templates/layoutsinteractionDetailsTabLayout.html
This way, you only need this line of code, assuming you are into a Servlet or Spring Controller or Struts 1/2 action or whatever called YourClass:
InputStream is = YourClass.class.getClassLoader().getResourceAsStream("templates/layoutsinteractionDetailsTabLayout.html");
If you are really trying to use this file as an HTML template, you'll be much better off to leverage Vaadin's support for this. They have a CustomLayout which loads an HTML template from your theme.
Your template would go into a folder like the following:
VAADIN/themes/mytheme/layout/layoutsinteractionDetailsTabLayout.html
Note that mytheme is the name of your theme and layout is a specially recognized Vaadin directory within themes.
Your custom component would then look like:
public class InteractionDetailsTabLayout extends CustomLayout {
private static final String TEMPLATE = "layoutsinteractionDetailsTabLayout";
public InteractionDetailsTabLayout() {
super(TEMPLATE);
}
}
Note that the super constructor argument excludes the directory and file suffix.
If you actually want to load a file in your webapp, don't bother with it in your VAADIN directory but instead put it in your classpath resources and access it with the ClassLoader.

In java, how do you retrieve images from a jar file?

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.)

Categories