Java windows user home directory

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"; 

Do not do this. If the user has moved the desktop, this will not work! If you have a solid state C: drive it is quite common to move the desktop onto a different drive. This stops lots of writes to the SSD (reads don’t reduce the lifetime, writes do) and it means you can have a small C: drive and a large normal one.

On windows 7, at least, ‘user.home’ is set by a registry value at JVM startup. If you’ve moved your desktop in a ‘normal’ manor then using the above method should ‘just work’. Also I’m pretty sure it actually looks for desktop when setting ‘user.home’ and then goes 1 directory up the path.

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.

Читайте также:  Python warnings format warning

The link mentioned above gives the correct answer. File home = FileSystemView.getFileSystemView().getHomeDirectory(); and then if you need it as a string home.getAbsolutePath();

javax.swing.filechooser.FileSystemView.getFileSystemView().getHomeDirectory() 

Am not personally fan of mixing swing with core java. So, I was looking if you can change it to something more core java.

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); 

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.

You’re just missing «C:\\Users\\» :

String userDefPath = "C:\\Users\\" + System.getProperty("user.name") + "\\Desktop"; 

This won’t work in some instances where C is not the right drive. Hardcoded paths are generally not a good idea anyway.

Did you know some better than using paths if you know please tell me i need that too but my way that i answer it’s working fine with me.

Please not that this question is 12 years old and current Windows options might not have been available back then. Also, whilest not recommended, you can install Windows on another drive than C:.

Источник

Get the User Home Directory in Java

Get the User Home Directory in Java

  1. Get the User’s Home Directory Using the System.getProperty() Method in Java
  2. Get the User’s Home Directory Using the Apache CommonsIO Library in Java
  3. Get the User’s Home Directory Using the System.getenv() Method in Java
  4. Summary

This tutorial introduces how to get the user home directory in Java and lists some example codes to guide you on the topic.

For a multi-user operating system, there exists a file system directory for every user; this directory is known as the user’s home directory. There are different ways to find the user home directory in Java. Let’s look at each one of them.

Get the User’s Home Directory Using the System.getProperty() Method in Java

The System class in Java has a Properties object used to store different properties and configurations of the current working environment. It also holds the user’s home directory.

We can access these properties by using the getProperty() method of this class. We need to pass the name of the system property that we want to view. In our case, it would be user.home .

The following code demonstrates how it works.

public class Main   public static void main(String[] args)    String userHomeDir = System.getProperty("user.home");  System.out.printf("The User Home Directory is %s", userHomeDir);  > > 
The User Home Directory is C:\Users\Lenovo 

If you’re curious and want to view all the system properties, you can use the getProperties() method. The code for the getProperties() method is shown below.

import java.util.Map; import java.util.Properties; public class Main   public static void main(String[] args)    Properties props = System.getProperties();  for(Map.EntryObject, Object> prop : props.entrySet())  System.out.println("Property: +" + prop.getKey() + "\tValue: " + prop.getValue());  > > 

Get the User’s Home Directory Using the Apache CommonsIO Library in Java

Apache Commons is a very powerful library, and the FileUtils class of the CommonsIO library can be used to fetch the home directory.

We can simply use the getUserDirectory() method of this class to view the user’s home directory. It returns a File object that represents the home directory. We can also get a String path of the home directory by using the getUserDirectoryPath() method.

The code and output for these methods are shown below.

import java.io.File; import org.apache.commons.io.FileUtils; public class Main   public static void main(String[] args)    File homeDir = FileUtils.getUserDirectory();  String homeDirPath = FileUtils.getUserDirectoryPath();  System.out.printf("The User Home Directory is %s\n", homeDir);  System.out.printf("The path of User Home Directory is %s", homeDirPath);  > > 
The User Home Directory is C:\Users\Lenovo The path of User Home Directory is C:\Users\Lenovo 

Get the User’s Home Directory Using the System.getenv() Method in Java

The getenv() method of the System class is used to get the value of system environment variables. We need to pass the name of the environment variable that we want to access.

To get the user’s home directory, we need to use the string USERPROFILE . The following program demonstrates the working of the getenv() method.

public class Main   public static void main(String[] args)    String userHomeDir = System.getenv("USERPROFILE");  System.out.printf("The User Home Directory is %s", userHomeDir);  > > 
The User Home Directory is C:\Users\Lenovo 

You can also use this method to view all the environment variables. Run the following program if you are curious to know more about your system’s environment variables.

import java.util.Map; public class Main   public static void main(String[] args)    MapString, String> envVars = System.getenv();  for(Map.EntryString, String> var : envVars.entrySet())  System.out.println(var.getKey() + " ---> " + var.getValue());  > > 

Summary

In this guide, we learn how to get the user’s home directory in Java. For some Windows platforms running older Java versions (before Java 8), the System.getProperty() method may not give the desired result due to the presence of a bug with ID 4787931.

Another similar bug (Bug ID 6519127) also exists. Because of this, the getProperty() method gives undesirable results. However, both of these bugs have already been resolved.

In most cases, the getProperty() method will work just fine, but we can use the alternative System.getenv() method to get the user home directory.

Related Article — Java Home

Related Article — Java Directory

Источник

What is the best way to find the user’s home directory in Java?

What is the best way to find the user’s home directory in Java? The difficulty is that the solution should be cross-platform; it should work on Windows 2000, XP, Vista, OS X, Linux, and other Unix variants. I am looking for a snippet of code that can accomplish this for all platforms, and a way to detect the platform. Per Java bug 4787931, system property user.home does not work correctly on Windows XP, so using this system property is not an acceptable solution as it is not cross-platform.

bug 4787931 for java versions up through 1.4.2 shows up again as bug 6519127 for java 1.6. The problem is not going away and is still listed as low priority.

9 Answers 9

The bug you reference (bug 4787391) has been fixed in Java 8. Even if you are using an older version of Java, the System.getProperty(«user.home») approach is probably still the best. The user.home approach seems to work in a very large number of cases. A 100% bulletproof solution on Windows is hard, because Windows has a shifting concept of what the home directory means.

If user.home isn’t good enough for you I would suggest choosing a definition of home directory for windows and using it, getting the appropriate environment variable with System.getenv(String) .

Apache has an excellent wrapper for System.getProperty calls that I recommend using. The correct call under that would be SystemUtils.getUserHome() .

Источник

Оцените статью