Java call for Windows API GetShortPathName

2020-03-25 08:20发布

问题:

I'd like to use native windows api function in my java class.

The function I am interested in is GetShortPathName. http://msdn.microsoft.com/en-us/library/aa364989%28VS.85%29.aspx

I tried to use this - http://dolf.trieschnigg.nl/eightpointthree/eightpointthree.html but in some conditions java crashes completely when I use it, so it is not the option for me.

The question is Do I have to write code in e.g C, make DLL and then use that DLL in JNI/JNA? Or maybe I somehow can access the system API in different way?

I will appreciate your comments. If maybe you could post some code as the example I would be grateful.

...

I found the answer using JNA



import com.sun.jna.Native;
import com.sun.jna.platform.win32.Kernel32;

public class Utils {

    public static String GetShortPathName(String path) {
        byte[] shortt = new byte[256];

        //Call CKernel32 interface to execute GetShortPathNameA method
        int a = CKernel32.INSTANCE.GetShortPathNameA(path, shortt, 256);
        String shortPath = Native.toString(shortt);
        return shortPath;

    }

    public interface CKernel32 extends Kernel32 {

        CKernel32 INSTANCE = (CKernel32) Native.loadLibrary("kernel32", CKernel32.class);

        int GetShortPathNameA(String LongName, byte[] ShortName, int BufferCount);
    }

}

回答1:

Thanks for hint. Following is my improved function. It uses Unicode version of the GetShortPathName

import com.sun.jna.Native;
import com.sun.jna.platform.win32.Kernel32;

public static String GetShortPathName(String path) {
    char[] result = new char[256];

    Kernel32.INSTANCE.GetShortPathName(path, result, result.length);
    return Native.toString(result);
}