简体   繁体   中英

Eclipse dynamic web project with Java: where to store and how reference datasets?

I´m developing a web project in eclipse with a servlet in the backend (using tomcat 8). In the servlet i want to reference two large files which contain data that should be read. Until now i was just using hardcoded filepaths as strings to reference the files , eg like this: "C:\\\\data\\\\file1"

I want to store the files within the project, so that the relative path to them stays the same no matter on which computer i´m running the application.

This subject came up sometimes here and i´ve tried out things like

System.getProperty("catalina.base");

or

System.getProperty("user.dir");

but both methods point to completely different locations then where my files are stored.

So if the file is stored in the project like this:

"server\\webapps\\project\\data\\file1"

and the servlet is contained in the package folder with the other .java files, how can i get the path to file1 as a string?

If the file is part of the webapp, you must not consider it as a file on the file system. A Java EE webapp is deployed as a war file, which is basically a zip file. Some servers extract this war file to the disk, some don't, but you don't need to care, because the Java API provides everything you need to read resources embedded in the application.

If it is, in the deployed archive, inside WEB-INF/classes, then it is part of the classpath of the application must be loaded using the class loader:

InputStream in = MyServlet.class.getResourceAsStream("/com/foo/bar/file.txt");

where com.foo.bar is the package where the file is located. For a file to end up at that location in the archive, you would put it, with the Java source files, in the package com.foo.bar . Eclipse will "compile" this file by simply copying it.

If it is elsewhere in the archive, for example in /WEB-INF/file.txt , then you should use

InputStream in = servletContext.getResourceAsStream("/WEB-INF/file.txt");

To end up in /WEB-INF/ inside the archive, the file should be located, in a typical eclipse project, in WebContent/WEB-INF .

I found a simple solution in this topic: how to load/reference a file as a File instance from the classpath

Except i´m not converting the URL object into a URI but into a string. Haven´t tested it on another server, but at least it works as it should for now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM