mynameishi
mynameishi

Reputation: 59

creating folders for all users

I am trying to create a folder by running java. As of now I have this and it works.

File f = new File ("/Users/myName/Desktop/nameOfDir");
f.mkdirs();

The question is what happens when I send this code to my friend? Would he have to change the code to the below for it to work?

File f = new File ("/Users/myFriendsName/Desktop/nameOfDir");
f.mkdirs();

how can I make the program find the correct path and create the folder where I want it (the desktop), regardless of who the user is?

Also, after creating the folder I will have to create a .txt in the folder. I can do this now, but same problem arise concerning different user names.

Upvotes: 0

Views: 237

Answers (2)

Andy Turner
Andy Turner

Reputation: 140329

You can get the path to a user's home directory in a platform-independent way using:

System.getProperty("user.home");

So:

File f = new File(System.getProperty("user.home"), "Desktop/nameOfDir");
f.mkdirs();

Upvotes: 1

Alessandro
Alessandro

Reputation: 886

try using the following:

String userName = System.getProperty("user.name"); //platform independent 
File f = new File ("/Users/" + userName + "/Desktop/nameOfDir");
f.mkdirs();

Upvotes: 1

Related Questions