- How to get the Desktop path in java
- Solution 2
- Solution 3
- Solution 4
- Solution 5
- How to get the Desktop path in Java
- Using the System Property
- Using the FileSystemView Class
- Using the Desktop Class
- How to get the desktop path in java?
- Method 1: Using the System Properties
- Method 2: Using the FileSystemView Class
- Method 3: Using the JNA Library
- Method 4: Using a Third-Party Library
- User desktop path java
How to get the Desktop path in java
I use a french version of Windows and with it the instruction:
System.getProperty("user.home") + "/Desktop";
Solution 2
I think this is the same question. but I’m not sure!:
Reading it I would expect that solution to return the user.home, but apparently not, and the link in the answer comments back that up. Haven’t tried it myself.
I guess by using JFileChooser the solution will require a non-headless JVM, but you are probably running one of them.
Solution 3
This is for Windows only. Launch REG.EXE and capture its output :
import java.io.*; public class WindowsUtils < private static final String REGQUERY_UTIL = "reg query "; private static final String REGSTR_TOKEN = "REG_SZ"; private static final String DESKTOP_FOLDER_CMD = REGQUERY_UTIL + "\"HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\" + "Explorer\\Shell Folders\" /v DESKTOP"; private WindowsUtils() <>public static String getCurrentUserDesktopPath() < try < Process process = Runtime.getRuntime().exec(DESKTOP_FOLDER_CMD); StreamReader reader = new StreamReader(process.getInputStream()); reader.start(); process.waitFor(); reader.join(); String result = reader.getResult(); int p = result.indexOf(REGSTR_TOKEN); if (p == -1) return null; return result.substring(p + REGSTR_TOKEN.length()).trim(); >catch (Exception e) < return null; >> /** * TEST */ public static void main(String[] args) < System.out.println("Desktop directory : " + getCurrentUserDesktopPath()); >static class StreamReader extends Thread < private InputStream is; private StringWriter sw; StreamReader(InputStream is) < this.is = is; sw = new StringWriter(); >public void run() < try < int c; while ((c = is.read()) != -1) sw.write(c); >catch (IOException e) < ; >> String getResult() < return sw.toString(); >> >
Shell32.INSTANCE.SHGetFolderPath(null, ShlObj.CSIDL_DESKTOPDIRECTORY, null, ShlObj.SHGFP_TYPE_CURRENT, pszPath);
Solution 4
javax.swing.filechooser.FileSystemView.getFileSystemView().getHomeDirectory()
Solution 5
But you could try to find an anwser browsing the code of some open-source projects, e.g. on Koders. I guess all the solutions boil down to checking the HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders\Desktop path in the Windows registry. And probably are Windows-specific.
If you need a more general solution I would try to find an open-source application you know is working properly on different platforms and puts some icons on the user’s Desktop.
How to get the Desktop path in Java
There are several ways to retrieve the path of the Desktop folder in Java. Here are a few code examples that demonstrate how to get the path of the Desktop folder in Java.
Using the System Property
One way to retrieve the path of the Desktop folder is to use the `user.home` system property. The code snippet below demonstrates how to retrieve the path of the Desktop folder using this method.
String desktopPath = System.getProperty("user.home") + "/Desktop"; System.out.println(desktopPath);
Using the FileSystemView Class
Another way to retrieve the path of the Desktop folder is to use the `FileSystemView` class. This class provides a platform-dependent view of the file system, and can be used to retrieve the path of the Desktop folder. The code snippet below demonstrates how to retrieve the path of the Desktop folder using this method.
FileSystemView view = FileSystemView.getFileSystemView(); File desktop = view.getHomeDirectory(); String desktopPath = desktop.getAbsolutePath(); System.out.println(desktopPath);
Using the Desktop Class
The `Desktop` class provides a way to interact with the desktop of the native operating system. This class can also be used to retrieve the path of the Desktop folder. The code snippet below demonstrates how to retrieve the path of the Desktop folder using this method.
Desktop desktop = Desktop.getDesktop(); File desktopDir = desktop.getDesktopDirectory(); String desktopPath = desktopDir.getAbsolutePath(); System.out.println(desktopPath);
These are some of the ways to retrieve the path of the Desktop folder in Java. Using any of these methods, you can easily access the Desktop folder and perform file operations.
How to get the desktop path in java?
In Java, it is often necessary to access the file system in order to read or write files. One common use case is accessing the user’s desktop directory. However, determining the correct path to the desktop can be tricky, as it depends on the operating system and user configuration. In this article, we will explore several methods for retrieving the desktop path in Java.
Method 1: Using the System Properties
To get the Desktop path in Java using the System Properties, you can use the following code:
String desktopPath = System.getProperty("user.home") + "/Desktop";
This code retrieves the user’s home directory using the user.home system property and appends /Desktop to it to get the path to the Desktop folder.
Alternatively, you can use the FileSystemView class from the javax.swing.filechooser package to get the Desktop path:
FileSystemView view = FileSystemView.getFileSystemView(); File desktop = view.getHomeDirectory(); String desktopPath = desktop.getAbsolutePath();
This code retrieves the FileSystemView for the current system, gets the user’s home directory using the getHomeDirectory() method, and gets the absolute path of the Desktop folder using the getAbsolutePath() method.
You can also use the Desktop class from the java.awt package to get the Desktop path:
Desktop desktop = Desktop.getDesktop(); File desktopDir = desktop.getDesktopDirectory(); String desktopPath = desktopDir.getAbsolutePath();
This code retrieves the Desktop object for the current system, gets the Desktop directory using the getDesktopDirectory() method, and gets the absolute path of the Desktop folder using the getAbsolutePath() method.
In summary, there are multiple ways to get the Desktop path in Java, and using the System Properties, the FileSystemView class, and the Desktop class are three possible options.
Method 2: Using the FileSystemView Class
To get the Desktop path in Java using the FileSystemView class, you can follow these steps:
import javax.swing.filechooser.FileSystemView;
FileSystemView fileSystemView = FileSystemView.getFileSystemView();
File homeDirectory = fileSystemView.getHomeDirectory();
- Use the getFileSystemView() method of the FileSystemView class to get the file system view for the home directory:
FileSystemView homeDirectoryFileSystemView = fileSystemView.getFileSystemView(homeDirectory);
- Use the getSystemDisplayName() method of the FileSystemView class to get the display name of the home directory:
String homeDirectoryDisplayName = homeDirectoryFileSystemView.getSystemDisplayName(homeDirectory);
- Use the getParentDirectory() method of the FileSystemView class to get the parent directory of the home directory:
File parentDirectory = homeDirectoryFileSystemView.getParentDirectory(homeDirectory);
- Use the getSystemDisplayName() method of the FileSystemView class again to get the display name of the parent directory:
String parentDirectoryDisplayName = homeDirectoryFileSystemView.getSystemDisplayName(parentDirectory);
String desktopPath = parentDirectoryDisplayName + "\\" + homeDirectoryDisplayName;
Here is the complete code:
import javax.swing.filechooser.FileSystemView; import java.io.File; public class DesktopPath public static void main(String[] args) FileSystemView fileSystemView = FileSystemView.getFileSystemView(); File homeDirectory = fileSystemView.getHomeDirectory(); FileSystemView homeDirectoryFileSystemView = fileSystemView.getFileSystemView(homeDirectory); String homeDirectoryDisplayName = homeDirectoryFileSystemView.getSystemDisplayName(homeDirectory); File parentDirectory = homeDirectoryFileSystemView.getParentDirectory(homeDirectory); String parentDirectoryDisplayName = homeDirectoryFileSystemView.getSystemDisplayName(parentDirectory); String desktopPath = parentDirectoryDisplayName + "\\" + homeDirectoryDisplayName; System.out.println(desktopPath); > >
This code should output the path to the Desktop.
Method 3: Using the JNA Library
To get the desktop path in Java using the JNA Library, you can follow these steps:
- Add the JNA Library dependency to your project.
- Import the necessary JNA classes in your Java code.
- Define the shell32 interface using the JNA Library.
- Define the necessary shell32 functions using the JNA Library.
- Call the shell32 functions to get the desktop path.
Here is an example code snippet that demonstrates how to get the desktop path using the JNA Library in Java:
import com.sun.jna.platform.win32.Shell32; import com.sun.jna.platform.win32.WinDef; import com.sun.jna.platform.win32.WinNT; import com.sun.jna.ptr.PointerByReference; public class DesktopPathExample public static void main(String[] args) // Define the shell32 interface Shell32 shell32 = Shell32.INSTANCE; // Define the necessary shell32 functions WinNT.HRESULT hresult = shell32.SHGetFolderPath( null, Shell32.CSIDL_DESKTOPDIRECTORY, null, Shell32.SHGFP_TYPE_CURRENT, path ); // Check if the function call was successful if (hresult.intValue() == 0) // Get the desktop path from the pointer reference String desktopPath = path.getValue(); // Print the desktop path System.out.println("Desktop path: " + desktopPath); > else // Print an error message System.out.println("Failed to get desktop path"); > > >
In this example code, we first import the necessary JNA classes. Then, we define the shell32 interface and the necessary shell32 functions. We call the SHGetFolderPath function with the Shell32.CSIDL_DESKTOPDIRECTORY parameter to get the desktop path. Finally, we check if the function call was successful and print the desktop path.
Note that the SHGetFolderPath function returns an HRESULT value, which is a standard return value in Windows programming. An HRESULT value of 0 indicates success, while any other value indicates an error.
Method 4: Using a Third-Party Library
To get the Desktop path in Java using a third-party library, we can use the Apache Commons IO library. Here are the steps to do it:
- First, we need to add the Apache Commons IO library to our project. We can do this by adding the following dependency to our project’s pom.xml file:
dependency> groupId>commons-iogroupId> artifactId>commons-ioartifactId> version>2.8.0version> dependency>
- Once we have added the dependency, we can use the FileUtils class to get the Desktop path. Here is the code to do it:
import org.apache.commons.io.FileUtils; public class GetDesktopPath public static void main(String[] args) String desktopPath = FileUtils.getUserDirectoryPath() + "/Desktop"; System.out.println("Desktop Path: " + desktopPath); > >
In this code, we are using the getUserDirectoryPath() method to get the user’s home directory path, and then appending «/Desktop» to it to get the Desktop path.
- We can also use the SystemUtils class from the Apache Commons Lang library to get the Desktop path. Here is the code to do it:
import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.SystemUtils; public class GetDesktopPath public static void main(String[] args) String desktopPath = SystemUtils.getUserHome() + "/Desktop"; System.out.println("Desktop Path: " + desktopPath); > >
In this code, we are using the getUserHome() method from the SystemUtils class to get the user’s home directory path, and then appending «/Desktop» to it to get the Desktop path.
These are the two ways to get the Desktop path in Java using a third-party library.
User desktop path java
Path testFile = Paths.get(«C:\\Users\\jleom\\Desktop\\java\\javarush task\\test.txt»); Path testFile2 = Paths.get(«C:\\Users\\jleom\\Desktop»); System.out.println(testFile.relativize(testFile2));
Класс Path и класс Paths предназначены для работы с файловой системой в Java, однако они предоставляют разные функции и методы. Path — это интерфейс, который определяет методы для работы с путями к файлам и каталогам в файловой системе. Он предоставляет ряд методов для работы с путями, таких как resolve(), relativize(), getParent(), getFileName(), toAbsolutePath() и другие. Paths — это утилитный класс, который предоставляет статические методы для создания экземпляров класса Path. Он не имеет методов для работы с путями напрямую, но предоставляет методы для создания экземпляров Path из строковых значений или URI. Еще методы по классу Paths: getFileSystem(): возвращает объект FileSystem, представляющий файловую систему, которой принадлежит данный путь. getDefault(): возвращает объект FileSystem, представляющий файловую систему по умолчанию. getTempDirectory(): возвращает объект типа Path, представляющий временный каталог. getHomeDirectory(): возвращает объект типа Path, представляющий домашний каталог пользователя. exists(Path path, LinkOption. options): проверяет, существует ли файл или каталог, представленный указанным путем. Класс Paths удобен для работы с файловой системой, так как он предоставляет простой и удобный API для работы с путями.
Надо добавить в статью, Paths.get был в 8 Java. Потом появился Path.of. Если у вас не работает Path.of (версия Java не позволяет), только тогда нужен Paths.get