In this brief tutorial, we’ll learn two ways to get the desktop path in Java. The first way is with the System.getProperty() method, and the second way uses the getHomeDirectory() method of the FileSystemView class.
2. Using System.getProperty()
Java’s System class offers the Properties object, which stores different configurations and properties of the current working environment. We’re interested in one particular property for our case: the user.home property that holds the user’s home directory. This property can be retrieved using theSystem.getProperty() method, which allows getting the value of a specific system property.
Let’s see an example of how to use the user.home property and get the desktop path in Java:
String desktopPath = System.getProperty("user.home") + File.separator +"Desktop";
To get the desktop path, we have to add the “/Desktop” string after the property value of user.home.
3. Using FileSystemView.getHomeDirectory()
Another way to get the desktop path in Java is to use the FileSystemView class, which provides valuable information about the file system and its components. Furthermore, we can use the getHomeDirectory() method to get the user’s home directory as a File object.
Let’s see how to benefit from this class to get the desktop path:
FileSystemView view = FileSystemView.getFileSystemView(); File file = view.getHomeDirectory(); String desktopPath = file.getPath();
In our example, we first use the getFileSystemView() method to get an instance of the FileSystemView class, and second, we call the getHomeDirectory() method on that instance to get the user’s home directory as a File object. Finally, we use the File.getPath() method to get the desktop path as a String.
In this quick article, we explained how to get the desktop path in Java using two approaches. The first uses the System.getProperty() method to get the user.home property from the system, and the second one uses the getHomeDirectory() method of the FileSystemView class.
As always, the code is available over on GitHub.