简体   繁体   中英

How to create a file in a eclipse project directory without knowing the exact path?

I have a java class in my Eclipse web-app project that generate a XML file. This xml file will be used to display its content in a JSP page through an AJAX call. Suppose I want to export the project and send it to another user who will then use it on another PC. How can I create the xml file in the project directory even though I don't know the path it will have on the new computer?

Most Java projects have a standardized project structure. eg Maven looks like follows:

my-app
|-- pom.xml
`-- src
    |-- main
    |   |-- java
    |   |   `-- com
    |   |       `-- mycompany
    |   |            `-- app
    |   |               `-- App.java
    |   `-- resources
    |
    `-- test
        `-- java
            `-- com
                `-- mycompany
                    `-- app
                        `-- AppTest.java

Files a Java application will create with a relative path will read from the resources folder when run locally (of course this can be configures in the runtime environment in Eclipse or tweaked in the java/javac CLI command). Note a packaged Java program cannot write into the packaged JAR or WAR file. So when creating a JAR/WAR you can embed static content, but writing doesn't work. So when you run JSP pages classloading comes into play. Different uses get sandboxed to their own context on the server side. Therefore sharing the same file and/or disk space might not be a good idea in overall.

When you have a file DB or similar, you should have a server configuration variable to set the path to the value that's used on your server. The complete configuration in your JSP environment is handeled in the web.xml file: https://docs.oracle.com/cd/E13222_01/wls/docs81/webapp/web_xml.html

It's the standard way for J2EE containers by the way.

If you have a local project and not a fully blown production environment, the simplest options might be reading out an environment variable with the local path you want to use on your machine.

Note that if you want to write a file from your J2EE container (=the software that's running the JSP) there might be security rules needed you need to set in Tomcat/Glassfish/Wildfly/...

One way is to pass the path as a system property -Dproperty=value (eg java -DxmlDir="C:\xml" SomeClass). On Eclipse, you can add this in Run Configurations, then I think it was either in Arguments or Environment. To access the property, simply do System.getProperty("xmlDir") . On the new computer, they can specify where ever they want the XML file to reside.

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