29

I have a DownloadTask class in java that takes a filename and URL, downloads that file and saves it to the downloads folder.

To save it to my downloads folder, I have the line

File file = new File("/users/myName/Downloads" + fileName + ".txt");

What can I replace this path with so that anyone can run the program and the file will be saved to their downloads folder?

ajspencer
  • 1,017
  • 1
  • 10
  • 21
  • For Linux and similar systems, see https://stackoverflow.com/questions/22250118/using-xdg-directory-specification-on-java-application – Nova Jan 21 '21 at 18:24
  • 1
    Does this answer your question? [How can I get system user documents, pictures, music folders independent of OS using Java?](https://stackoverflow.com/questions/2896610/how-can-i-get-system-user-documents-pictures-music-folders-independent-of-os-u) – Nova Jan 21 '21 at 18:24

2 Answers2

58

Check out this question. Use...

String home = System.getProperty("user.home");
File file = new File(home+"/Downloads/" + fileName + ".txt"); 
Community
  • 1
  • 1
Harsh Poddar
  • 2,394
  • 18
  • 17
  • 3
    This is actually not a reliable way to get the Downloads folder in Windows, because users can change the folder (so that it is *not* under their home directory anymore). See here: https://blog.samirhadzic.com/2018/03/01/get-the-user-download-folder-path/ – Zymox Oct 26 '20 at 10:44
  • Composing a path string with "/" may not work on platforms with a different separator character. Use this instead: File f = new File(new File(home, "Downloads"), fileName + ".txt); – Adam Gawne-Cain May 28 '21 at 10:00
3

Your own folder is accessible using the $HOME environment variable.

In Java, you can find you home folder using the user.home system property. See Java system properties.

e.g.:

System.getProperty("user.home");
rghome
  • 8,529
  • 8
  • 43
  • 62