简体   繁体   English

如何获取现有文件夹的绝对路径

[英]How to get absolute path of existing folder

I have a test data folder in my java project... something like this 我的Java项目中有一个测试数据文件夹...类似这样

Project 项目

  • src Folder src文件夹
  • testData Folder testData文件夹

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. 如何使用java获取数据文件夹,以前我们已经在常量中对进行了硬编码,但是现在我们使用的是CI工具,我想避免使用硬编码的路径。

its is very fine to hardcode the testdata folder, but the point is that it should be a relative path: 硬编码testdata文件夹是非常好的,但是要点是它应该是相对路径:

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(). Java文件对象将提供getPath(),getAbsolutePath()和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. 如果要在Windows / Linux / Mac / etc之间进行交换,则可能在转换源和目标之间的路径时遇到问题。 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 对于src

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

For testdata :- 对于testdata : -

static String TEST_PATH = "./testdata/";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM