简体   繁体   中英

Reading files from relative paths on Tomcat

I need to run a web-app on Tomcat, but it cannot read the txt files(from a relative paths as below) on Tomcat. However, it does work if I use a full path.

So I am wondering where can I put these txt files so that when Tomcat started, the app can successfully read the txt files from a relative path.

Currently, the project structure is as follows, the txt files is located on the same directory as src file in Project Explorer in Eclipse .

Project_Name
src
   java files

EDGES.txt
NODES.txt

The code is as follows, I am appreciated if someone can give me an answer in details, since I am quite new to Java.

The code is as follows:

public class RouteingDao {
    NodeJSONReader nodeInput = new NodeJSONReader("NODES.txt");
    EdgeJSONReader edgeInput = new EdgeJSONReader("EDGES.txt");
    ...
}

The NodeJSONReader/EdgeJSONReader class is as follows:

public class EdgeJSONReader {
    private EdgeEntity[] edgeEntity;

    // constructor
    public EdgeJSONReader(String JSON_FILE) {
        edgeEntity = readEntityFromFile(JSON_FILE);
    }

    // load the JSON data from local file 
    public EdgeEntity[] readEntityFromFile(String JSON_FILE) {
        try {
            Reader reader = new FileReader(JSON_FILE);
            Gson gson = new Gson();
            edgeEntity = gson.fromJson(reader, EdgeEntity[].class);
        } 
        ...
    }
}

If you are using a servlet, then access the servlet context and the getRealPath method.

this.getServletContext().getRealPath("WEB-INF/nodes.txt")

The relative path sent to getRealPath will be expanded to the location of the files for your web app. You can add any path you like, even to a hidden file in WEB-INF.

From a JSP you can use

${pageContext.servletContext.getRealPath("WEB-INF/nodes.txt")}

Be careful, this will be in the build directory, so any changes to nodes.txt will not be saved to the original file.

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