简体   繁体   中英

How to read file with relative path from project root folder in Java?

I need to read an XML file from project root from my java class in inner folder.

Suppose the XML file is in

D:\\MyProjects\\TestProject

folder. And I need to read it from

D:\\MyProjects\\TestProject\\src\\main\\java\\com\\my\\test\\ReadXML.java

Here TestProject is my project root folder. src\\main\\java is my source folder and com.my.test is package inside it.

Please provide a way to read data from file in project root,

Thanks.

Java does not know where your project root is. It only knows which directory you are invoking it from.

If you are running from your root directory, then you can just use the file name directly, as MadProgrammer mentioned in his comment.

If you are not running from your project root, you will have to pass it in as a command line argument, if you do not want to hardcode an absolute path.

If you happen to know that you will always run from the same directory relative to the project root, for example <PROJECT_ROOT>/bin , then you can use a fixed relative path: ..\\Foo.xml .

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