我认为这只适用于英语Windows安装:
System.getProperty("user.home") + "/Desktop";
Run Code Online (Sandbox Code Playgroud)
如何让这个非英语Windows工作?
小智 41
我使用法语版的Windows并使用它的指令:
System.getProperty("user.home") + "/Desktop";
Run Code Online (Sandbox Code Playgroud)
对我来说很好.
我认为这是同一个问题......但我不确定!:
在Windows下的java中,如何找到重定向的Desktop文件夹?
阅读它我会期望该解决方案返回user.home,但显然不是,并且答案中的链接评论回来了.我自己没试过.
我想通过使用JFileChooser该解决方案将需要一个非无头JVM,但你可能正在运行其中一个.
javax.swing.filechooser.FileSystemView.getFileSystemView().getHomeDirectory()
Run Code Online (Sandbox Code Playgroud)
这仅适用于Windows.启动REG.EXE并捕获其输出:
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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
或者你可以使用JNA(这里有完整的例子)
Shell32.INSTANCE.SHGetFolderPath(null,
ShlObj.CSIDL_DESKTOPDIRECTORY, null, ShlObj.SHGFP_TYPE_CURRENT,
pszPath);
Run Code Online (Sandbox Code Playgroud)