简体   繁体   中英

How to get absolute path of existing folder

I have a test data folder in my java project... something like this

Project

  • src Folder
  • testData Folder

How can I get the data folder using java, previously we have a hardcoded the in a constant, but now we are using a CI tool and I want to avoid the hardcoded path.

its is very fine to hardcode the testdata folder, but the point is that it should be a relative path:

At the top of the test class you can just write

static final String TEST_PATH = "./testdata/";

Note that this is relative to the project.

If you want to convert such a relative path to an absoulte one:

String absoluteTestPath = new File(TEST_PATH).getAbsolutePath();

Take the input parameter and create a new File Object. The Java file object will provide getPath(), getAbsolutePath(), and getCanonicalPath(). Be careful with the file systems. If you are swapping between Windows/Linux/Mac/etc, you may have issues with translating paths between source and destination. I assume you source and destination are on the same file system in the example below.

File f = new File(pathStr);
String absPath = f.getAbsolutePath();

如何使用路径

Paths.get("your-relative-path-here").toAbsolutePath()

好吧,我通过以下方式解决了我的问题

public static final String Path_TestData = System.getProperty("user.dir") + "\\TestData\\";

For src

static String SRC_PATH = new File(".").getCanonicalPath()+System.getParameter("file.separator")+SRC;
// where SRC is the name of your source folder

For testdata :-

static String TEST_PATH = "./testdata/";

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