我需要确定使用Java(tm)存储在Windows系统上的文件的短文件名。
有相关的问题和相关的答案。但是,我发布了此解决方案,因为它使用Java(tm)代码而不需要外部库。欢迎使用其他版本的Java和/或Microsoft(R)Windows(tm)解决方案。
主要概念在于通过运行时类从Java(tm)调用CMD:
在(“ [长文件名]”)中的%I使用cmd / c执行@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;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句