0

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.

mynameishi
  • 59
  • 7
  • Possible duplicate of [How to get the Desktop path in java](http://stackoverflow.com/questions/1080634/how-to-get-the-desktop-path-in-java) – ArcticLord Jan 06 '16 at 12:34
  • this is not a duplicate, (atleast not to the question linked), I dont ask how to create a folder, I ask how to get the path correct acording to the user – mynameishi Jan 06 '16 at 12:37

2 Answers2

1

try using the following:

String userName = System.getProperty("user.name"); //platform independent 
File f = new File ("/Users/" + userName + "/Desktop/nameOfDir");
f.mkdirs();
lulas
  • 860
  • 9
  • 29
  • Note that whilst the username is retrieved in a platform-independent way here, the path constructed for `f` will only work on certain platforms. – Andy Turner Jan 06 '16 at 12:57
1

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();
Andy Turner
  • 137,514
  • 11
  • 162
  • 243