0

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.

1
  • "but it doesn't work as I want" Can you describe why (those don't work the way you want)? Commented Aug 20, 2014 at 2:08

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

That is how my code is. But it doesnt right. It only return /home/root. But my code is somewhere else: /home/root/...../project/class.java
Do you want to create a folder where the root of your project is or where your class files are? The root of your project is not the same place as where your code is.
@TuanDang A File reference can be absolute or relative, until you use something like getCanonicalFile, it won't be resolved to a full path. Java is fully capable of using this as is and it should work just fine...
0

Use like that

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

Comments

0

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.)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.