Search code examples
javafilefilesystemspathname

What is a pathname string's prefix and its length in JAVA?


File.java uses a variable as:

private final transient int prefixLength;

And says, this is "abstract pathname's prefix".

File.java also have a constructor as:

public File(String pathname) {
        if (pathname == null) {
            throw new NullPointerException();
        }
        this.path = fs.normalize(pathname);
        this.prefixLength = fs.prefixLength(this.path);
    }

Here it is setting the variable prefixLength using fs.prefixLength() method.

Variable fs is defined in File.java as:

private static final FileSystem fs = DefaultFileSystem.getFileSystem();

Method getFileSystem() of DefaultFileSystem class returns object of UnixFileSystem. So method fs.prefixLength() actually calls prefixLength() method of UnixFileSystem. The prefixLength() method of UnixFileSystem is implemented as:

public int prefixLength(String pathname) {
        if (pathname.length() == 0) return 0;
        return (pathname.charAt(0) == '/') ? 1 : 0;
    }

Means this method will only return 0 or 1 Depending upon the length of the pathname or first character of the pathname.

My doubt is: What type of length it is, and what is its significance?


Solution

  • The idea behind prefixLength is to treat the part of file name indicating the location of the root of its path separately from the rest of the file name:

    c:\quick\brown\fox.java
    ^^^
    

    Above, prefix is c:\.

    UNIX implementation is straightforward, because only two initial locations are possible - the root / and the current directory (no prefix).

    Windows implementation, which supports \\, c:, c:\, and \ is shown below:

    public int prefixLength(String path) {
        char slash = this.slash;
        int n = path.length();
        if (n == 0) return 0;
        char c0 = path.charAt(0);
        char c1 = (n > 1) ? path.charAt(1) : 0;
        if (c0 == slash) {
            if (c1 == slash) return 2;  /* Absolute UNC pathname "\\\\foo" */
            return 1;                   /* Drive-relative "\\foo" */
        }
        if (isLetter(c0) && (c1 == ':')) {
            if ((n > 2) && (path.charAt(2) == slash))
                return 3;               /* Absolute local pathname "z:\\foo" */
            return 2;                   /* Directory-relative "z:foo" */
        }
        return 0;                       /* Completely relative */
    }