my name is GYAN
my name is GYAN

Reputation: 1289

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?

Upvotes: 2

Views: 1827

Answers (2)

Vitorlui
Vitorlui

Reputation: 770

It is not clear your questions, lets try to clarify:

  • 1) What type of length it is?
  • 2) What is its significance?

1)This length means if the filepath has the name with the bar or not. In the unix file systems it is important to know....

when "/user/some_folder" return 1
when "user/some_folder" return 0
when "" return 0

2) probably it is used when you try to access files inside this filepath to take the "/" into account..

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727047

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 */
}

Upvotes: 3

Related Questions