Osm*_*cis 9 java windows short-filenames
我需要使用Java(tm)确定存储在Windows系统上的文件的短文件名.
有相关问题及相关答案.但是,我发布了这个解决方案,因为它使用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)