如何使用 Java 在 Windows 中获取短文件名? [英] How to get short-filenames in Windows using Java?
问题描述
我需要使用 Java(tm) 确定存储在 Windows 系统上的文件的短文件名.
I need to determine the short-filenames of files, stored on a Windows system, using Java(tm).
推荐答案
Self Answer
有相关问题,有相关答案.然而,我发布了这个解决方案,因为它使用 Java(tm) 代码而不需要外部库.欢迎针对不同版本的 Java 和/或 Microsoft(R) Windows(tm) 提供其他解决方案.
Self Answer
There are related questions with related answers. I post this solution, however, because it uses Java(tm) code without the need for external libraries. Additional solutions for different versions of Java and/or Microsoft(R) Windows(tm) are welcome.
主要概念在于通过运行时类从Java(tm)调用CMD:
Main concept lies in calling CMD from Java(tm) by means of the runtime class:
cmd/c for %I in ("[长文件名]") do @echo %~fsI
cmd /c for %I in ("[long file name]") do @echo %~fsI
解决方案
在运行在 Windows 7 系统上的 Java SE 7 上测试(为简洁起见,代码已减少).
Solution
Tested on Java SE 7 running on Windows 7 system (Code has been reduced for brevity).
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;
}
这篇关于如何使用 Java 在 Windows 中获取短文件名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!