开发者

getCanonicalFile and getAbsoluteFile returns the current (project) directory instead of the expected one

开发者 https://www.devze.com 2023-01-27 19:13 出处:网络
I try to make a simple program that contains the function of browsing local file system. However, I met a problem when the address is directly input.

I try to make a simple program that contains the function of browsing local file system.

However, I met a problem when the address is directly input.

public void setWorkingDirectory(File newDir)
{
    try
    {
        //try to eliminate redundancy
        this.workingDir = newDir.getCanonicalFile();
    }
    catch (IOException e)
    {
        this.workingDir = newDir;
    }
}
开发者_JS百科

I need the absolute path to display on the screen. So I use getCanonicalFile(). Everything works fine except that when I input "D:" the workingDir will be set to the current project directory in Eclipse (I think it should be the current directory when executed independently, the example is "D:\EclipseWorkspace\workspace\FTPClient") but the File newDir contains exactly the same path ("D:") (I traced it).

If I input "C:" or "D:\", then everything is fine. I couldn't find any information about this on the Internet. Could anyone tell me what's going on here and how to solve the problem?

Thanks in advance.

EDIT: I work on Windows XP SP3 with Java 6 if that matters.


The path command

D:

indicates a change to the currently selected directory on disk D.

Whereas

D:\

indicates a change to the root directory of disk D.

This is basic Windows, you'd get the same results in a (CMD) console window.

If it really is an issue, you'd need to look at the filename and see if it terminates with a File.separator and if not, append one.


Not really know how to explain it, the getCanonicalFile() uses the getCanonicalPath() which is essentially calls the FileSystem.canonicalize(String path) method (this is an abstract method).

In Windows, the java.io.Win32FileSystem.canonicalize(String path) (which extends java.io.FileSystem) calls, essentially, one of the 2 native methods:

protected native String canonicalize0(String path)

OR

protected native String canonicalizeWithPrefix0(String canonicalPrefix, String pathWithCanonicalPrefix)

So, as Kris says, it's basic Windows function.

0

精彩评论

暂无评论...
验证码 换一张
取 消