Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get short-filenames in Windows using Java?

How to get the short-filename for a long-filename in Windows using Java?

I need to determine the short-filenames of files, stored on a Windows system, using Java(tm).

like image 452
Osmund Francis Avatar asked Sep 19 '13 11:09

Osmund Francis


People also ask

How to get file name from directory path in Java?

File. getPath() respectively. The getName() returns the name of the file or the directory. The getPath() returns the abstract pathname in the form of a pathname string.

How do I find a specific file in Java?

Searching files in Java can be performed using the File class and FilenameFilter interface. The FilenameFilter interface is used to filter files from the list of files. This interface has a method boolean accept(File dir, String name) that is implemented to find the desired files from the list returned by the java. io.

How do I get the filename from the file path?

To extract filename from the file, we use “GetFileName()” method of “Path” class. This method is used to get the file name and extension of the specified path string. The returned value is null if the file path is null. Syntax: public static string GetFileName (string path);


1 Answers

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.

Main Concept

Main concept lies in calling CMD from Java(tm) by means of the runtime class:

cmd /c for %I in ("[long file name]") do @echo %~fsI

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;
}
like image 155
Osmund Francis Avatar answered Oct 11 '22 02:10

Osmund Francis