简体   繁体   中英

can i get my eclipse project path using servlet or jsp code?

 <%=session.getServletContext().getRealPath("/") %>
        <%
            String path= session.getServletContext().getRealPath("/");

            FileOutputStream file = new FileOutputStream(path+"\\testingfile.txt");

        %>

The above code is my jsp code after i run this page it will show the following output.

C:\Users\Stark\Documents\Eclipse IDE\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\Demo\

Why i get this path ? instead of i want to get the following path which is i needed ...

C:\Users\Stark\Documents\Eclipse IDE\Demo

How to solve this ? i need this project location for uploading my files into this location so help me !

The reason why you are getting "weird" path is simple-You are using Eclipse. When you run an application on Eclipse, Eclipse side will create new path and run your app there. This is why "getRealPath("/")" is giving you weird path, because your app is now running on a temporary folder.

Why is Eclipse doing this? Here is What I think

  1. In this way, Eclipse can run your app faster(Cached App or codes etc...)
  2. Your Original code will keep in safe with any unnecessary changes made by Eclipse.

So how can I solve this issue?

I suggest you use "Properties" class for setting upload path. This way you can divide URL setting from your logic and your code will become easy to be maintained. And you won't encounter any unexpected "environmental" error like this, because your setting value will be fixed by your input.

Here is fixed code for using "Properties".

<%

Properties prop = new Properties();
InputStream input = null;

try {

    input = new FileInputStream("config.properties");

    // load a properties file
    prop.load(input);

    // get the property for upload path
    String path=prop.getProperty("path.upload");
    FileOutputStream file = new FileOutputStream(path+"\\testingfile.txt");

    //TODO:rest of your logic codes will come here.

} catch (IOException ex) {
    ex.printStackTrace();
} finally {
    if (input != null) {
        try {
            input.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
%>

You must create "config.properties" file as well. Here is the contents of the file.

path.upload=C:\Users\Stark\Documents\Eclipse IDE\Demo

I hope my answer will help you.

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