简体   繁体   English

如何获取文件的当前路径和文件的根项目?

[英]How to get the current path of a file and root project of the file?

Say I want to create a new folder somewhere in my project, so I would like to get the current working path where my code is running or the root path of the project. 假设我想在项目的某个地方创建一个新文件夹,所以我想获取代码正在运行的当前工作路径或项目的根路径。

I don't wanna to hardcode the path. 我不想对路径进行硬编码。 I used getAbsolute() or getCanonicalFile() or System.property("user.dir") but it doesn't work as I want. 我使用了getAbsolute()getCanonicalFile() getAbsolute()getCanonicalFile() System.property("user.dir")但它不能按我的意愿工作。

You can get the current working directory as 您可以将当前工作目录获取为

File cwd = new File("./");

If you then need to make this into an absolute path there is 如果您随后需要将其变为绝对路径,则可以

cwd.getAbsolutePath();

You can create a new directory there with 您可以在其中创建一个新目录

File newDir = new File(cwd, "newDirectory");
newDir.mkdir();

But my code is somewhere else: /home/root/...../project/class.java 但是我的代码在其他地方:/home/root/...../project/class.java

The current working directory is (usually) the directory where you start Java from. 当前的工作目录通常是您从中启动Java的目录。 This is completely unrelated to where the jar files are, and this in turn is completely unrelated to where the source code is. 这与jar文件的位置完全无关,而又与源代码的位置完全无关。

You need to set the current working directory properly when you start the Java program (not the compiler). 启动Java程序(而不是编译器)时,需要正确设置当前工作目录。

If you start from a shell, cd to where you need it to be. 如果从外壳程序开始,请使用cd到需要的位置。 If you start from an IDE, there should be a setting. 如果从IDE启动,则应该进行设置。

You can use a relative path to get the root of the project. 您可以使用相对路径来获取项目的根。 This code, 此代码,

new File("myFolder").mkdir();

will create a new folder called myFolder in the root of your project. 将在项目的根目录中创建一个名为myFolder的新文件夹。 If you don't specify an absolute path, the compiler will always go to the root of your project. 如果您未指定绝对路径,则编译器将始终转到项目的根目录。

If you want to work where your main class is (this is different from the root of your project), you can get the path of your main class like this: 如果要在主类所在的地方工作(这与项目的根目录不同),则可以这样获取主类的路径:

URL mainPath = Main.class.getResource("Main.class");

(Replace Main with the name of your main class.) (用您的主类名称替换Main。)

Use like that 这样使用

 Path path = Paths.get("");
 String s = path.toAbsolutePath().toString();
 System.out.println(s);

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

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