Pegando o caminho/path do desktop do usuário em java

Pegando o caminho/path do desktop do usuário:

String home = System.getProperty(“user.home”);

home += “\\Desktop”;

 

 

I know using .NET languages such as C#, one can do something like

Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory)

to find the redirected location of the Desktop. However, under Java, I cannot think of a good way to do this. What is the most appropriate way to find a redirected user Desktop directory from Java, without using JNI? The specific purpose here is for the purposes of managing a desktop shortcut, if the user wants one, for a Java Web Start application.

This application needs to write to the “Application Data” tree as well as optionally to the Desktop. I am making the assumption that %APPDATA% is always correctly populated, even when folders are redirected, for finding the “Application Data” tree. So my open question is how to reliably find the Desktop folder.

NOTE: I believe that the Java system property ${user.home} actually (and erroneously) locates the user’s Desktop directory via registry keys and then tries to navigate up one directory to find the “home” directory. This works fine when no directories are redirected, and otherwise may or may not return something useful.

 

FileSystemView filesys = FileSystemView.getFileSystemView();

File[] roots = filesys.getRoots();

filesys.getHomeDirectory()

 

 

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

 

 

No comments yet.