How does Java circumvent the windows MAX_PATH WinAPI limitation

Deadly 提交于 2020-01-11 09:20:31

问题


Does anyone know how Java is able to circumvent the windows MAX_PATH limitations. Using the below code I was able to create a really long path in Java and was able to perform I/O, which would have been impossible using windows without prefixing \\?\.

public static void main(String[] args) throws IOException {
    BufferedWriter bufWriter = null;
    try {
        StringBuilder s = new StringBuilder();
        for (int i = 0; i < 130; i++) {
            s.append("asdf\\");
        }
        String filePath = "C:\\" + s.toString();;
        System.out.println("File Path = " + filePath);
        File f = new File(filePath);
        f.mkdirs();
        f = new File(f, "dummy.txt");
        System.out.println("Full path = " + f);
        bufWriter = new BufferedWriter(new FileWriter(f));
        bufWriter.write("Hello"); 

    } 
    catch (Exception e) {
        e.printStackTrace();
    }
    finally {
        if (bufWriter != null) {
            bufWriter.close();
        }
    }
}

回答1:


From the JVM's canonicalize_md.c:

/* copy \\?\ or \\?\UNC\ to the front of path*/
WCHAR* getPrefixed(const WCHAR* path, int pathlen) {
    [download JVM source code (below) to see implementation]
}

The function getPrefixed is called:

  • by the function wcanonicalize if ((pathlen = wcslen(path)) > MAX_PATH - 1)
  • by the function wcanonicalizeWithPrefix.

I didn't trace the call chain farther than that, but I assume the JVM always uses these canonicalization routines before accessing the filesystem, and so always hits this code one way or another. If you want to trace the call chain farther yourself, you too can partake in the joys of browsing the JVM source code! Download at: http://download.java.net/openjdk/jdk6/




回答2:


Windows bypasses that limitation if the path is prefixed with \\?\.




回答3:


Most likely Java is in fact using UNC paths (\?) internally.



来源:https://stackoverflow.com/questions/10094365/how-does-java-circumvent-the-windows-max-path-winapi-limitation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!