1

How can you create a directory anywhere on your hard drive using Java? For Example, I would like to create a folder in the home folder of the computer. If I use this code:

File file = new File("~/test"); if (!file.exists()) { try { folder.mkdirs(); } catch(Exception e) { JOptionPane.showMessageDialog(null, "There was an error: \n"+e, "Error!", 1); } } 

it creates a folder name "~" and a folder inside that named "test" in the directory my project is in.

How can i get Java to create the folder in my home folder?

Thanks!

2
  • ~ is not going to be expanded by most (any?) Java APIs. Commented Apr 30, 2012 at 0:49
  • 1
    ~ is resolved by the shell (e.g. Bash). You'll need to use /home/xyz/test. Commented Apr 30, 2012 at 0:49

2 Answers 2

7

You can get the user directory path by getting the system property "user.home"

System.getProperty("user.home"); 
Sign up to request clarification or add additional context in comments.

5 Comments

Yes, this is the idea of the properties, allowing OS portability.
If I begin the path with a "/", will Java take that as an absolute path to the directory?
In unix, yes. didn't try it on windows but i guess you'll get FileNotFound exception
And on Windows if I start the path with "C:\\" it will take that as the absolute path?
Yes, the same goes for d:\\ etc.
3

~ is resolved by the shell (e.g. Bash), not by Java (AFAIK). You'll need to use /home/xyz/test.

1 Comment

So if I begin the path with a "/", Java will take that as an absolute path to the directory?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.