Reputation: 31
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.
Upvotes: 0
Views: 4837
Reputation: 994
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. 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.)
Upvotes: 0
Reputation: 262464
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
The current working directory is (usually) the directory where you start Java from. This is completely unrelated to where the jar files are, and this in turn is completely unrelated to where the source code is.
You need to set the current working directory properly when you start the Java program (not the compiler).
If you start from a shell, cd
to where you need it to be. If you start from an IDE, there should be a setting.
Upvotes: 4
Reputation: 2006
Use like that
Path path = Paths.get("");
String s = path.toAbsolutePath().toString();
System.out.println(s);
Upvotes: 0