Last active
August 8, 2021 14:43
-
-
Save tiagoengel/45a2f0f83bd19e37036703b328efcb57 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package systextil.commons.io.path; | |
import java.io.File; | |
import com.sun.jna.Library; | |
import com.sun.jna.Native; | |
import com.sun.jna.NativeMapped; | |
import com.sun.jna.PointerType; | |
import com.sun.jna.win32.W32APIOptions; | |
/*package*/ class WindowsPaths extends SystemPaths { | |
@Override | |
public File getCommonAppData(String appName) { | |
return join(getPath(Shell32.CSIDL_COMMON_APPDATA), appName); | |
} | |
@Override | |
public File getLocalAppData(String appName) { | |
return join(getPath(Shell32.CSIDL_LOCAL_APPDATA), appName); | |
} | |
private synchronized String getPath(int pathType) { | |
HWND hwndOwner = null; | |
int nFolder = pathType; | |
HANDLE hToken = null; | |
int dwFlags = Shell32.SHGFP_TYPE_CURRENT; | |
char[] pszPath = new char[Shell32.MAX_PATH]; | |
int hResult = Shell32.INSTANCE.SHGetFolderPath(hwndOwner, nFolder, hToken, dwFlags, pszPath); | |
if (Shell32.S_OK == hResult) { | |
String path = new String(pszPath); | |
int len = path.indexOf('\0'); | |
return path.substring(0, len); | |
} else { | |
throw new RuntimeException("Unable to load path. Error code: " + hResult); | |
} | |
} | |
private class HANDLE extends PointerType implements NativeMapped {} | |
private class HWND extends HANDLE {} | |
private interface Shell32 extends Library { | |
static final int MAX_PATH = 260; | |
static final int CSIDL_LOCAL_APPDATA = 0x001c; | |
static final int CSIDL_COMMON_APPDATA = 0x0023; | |
static final int SHGFP_TYPE_CURRENT = 0; | |
static final int S_OK = 0; | |
static Shell32 INSTANCE = (Shell32) Native.loadLibrary("shell32", Shell32.class, W32APIOptions.UNICODE_OPTIONS); | |
/** | |
* @see <a href="http://msdn.microsoft.com/en-us/library/bb762181(VS.85).aspx">SHGetFolderPath</a> | |
*/ | |
public int SHGetFolderPath(HWND hwndOwner, int nFolder, HANDLE hToken, int dwFlags, char[] pszPath); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment