Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java file path in web project

Tags:

java

file

I need to access the resource files in my web project from a class. The problem is that the paths of my development environment are different from the ones when the project is deployed.

For example, if I want to access some css files while developing I can do like this:

File file = new File("src/main/webapp/resources/styles/some.css/");

But this may not work once it's deployed because there's no src or main directories in the target folder. How could I access the files consistently?

like image 370
Sanghyun Lee Avatar asked Dec 16 '22 11:12

Sanghyun Lee


2 Answers

You seem to be storing your CSS file in the classpath for some unobvious reason. The folder name src is typical as default name of Eclipse's project source folder. And that it apparently magically works as being a relative path in the File constructor (bad, bad), only confirms that you're running this in the IDE context.

This is indeed not portable.

You should not be using File's constructor. If the resource is in the classpath, you need to get it as resource from the classpath.

InputStream input = getClass().getResourceAsStream("/main/webapp/resources/styles/some.css");
// ...

Assuming that the current class is running in the same context, this will work regardless of the runtime environment.

See also:

  • getResourceAsStream() vs FileInputStream

Update: ah, the functional requirement is now more clear.

Actually I want to get lastModified from the file. Is it possible with InputStream? –

Use getResource() instead to obtain it as an URL. Then you can open the connection on it and request for the lastModified.

URL url = getClass().getResource("/main/webapp/resources/styles/some.css");
long lastModified = url.openConnection().getLastModified();
// ...
like image 174
BalusC Avatar answered Dec 27 '22 01:12

BalusC


If what you're looking to do is open a file that's within the browser-visible part of the application, I'd suggest using ServletContext.getRealPath(...)

Thus:

File f = new File(this.getServletContext().getRealPath("relative/path/to/your/file"));

Note: if you're not within a servlet, you may have to jump through some additional hoops to get the ServletContext, but it should always be available to you in a web environment. This solution also allows you to put the .css file where the user's browser can see it, whereas putting it under /WEB-INF/ would hide the file from the user.

like image 24
Ian McLaird Avatar answered Dec 27 '22 01:12

Ian McLaird