如何使用Java在Windows中获取短文件名?

Osm*_*cis 9 java windows short-filenames

如何在Windows中使用Java获取长文件名的短文件名?

我需要使用Java(tm)确定存储在Windows系统上的文件的短文件名.

Osm*_*cis 9

自我答案

有相关问题及相关答案.但是,我发布了这个解决方案,因为它使用Java(tm)代码而不需要外部库.不同版本的Java和/或Microsoft(R)Windows(tm)的其他解决方案是受欢迎的.

主要概念

主要概念在于通过运行时类从Java(tm)调用CMD:

cmd/c for%I in("[long file name]")执行@echo%~fsi

在Windows 7系统上运行的Java SE 7上进行了测试(为简洁起见,代码已经减少).

    public static String getMSDOSName(String fileName)
    throws IOException, InterruptedException {

    String path = getAbsolutePath(fileName);

    // changed "+ fileName.toUpperCase() +" to "path"
    Process process =
        Runtime.getRuntime().exec(
            "cmd /c for %I in (\"" + path + "\") do @echo %~fsI");

    process.waitFor();

    byte[] data = new byte[65536];
    int size = process.getInputStream().read(data);

    if (size <= 0)
        return null;

    return new String(data, 0, size).replaceAll("\\r\\n", "");
}

public static String getAbsolutePath(String fileName)
    throws IOException {
    File file = new File(fileName);
    String path = file.getAbsolutePath();

    if (file.exists() == false)
        file = new File(path);

    path = file.getCanonicalPath();

    if (file.isDirectory() && (path.endsWith(File.separator) == false))
        path += File.separator;

    return path;
}
Run Code Online (Sandbox Code Playgroud)

  • 该解决方案非常好,但有一个小错误。fileName.toUpperCase() 应该删除 toUpperCase 因为该转换可能会进行一些与 Windows 字符集工作方式不兼容的转换。作为回报,Windows 可能找不到该文件。我有一个像“20140506_224702_Bäckerstraße.jpg”这样的文件名错误,通过转换变成了“20140506_224702_BÄCKERSTRASSE.JPG”。 (2认同)