Unable to get a correct relative path between two files, only when one path is a file and the other a directory, is this normal expected behavior?

StackOverflow https://stackoverflow.com/questions/23476378

  •  15-07-2023
  •  | 
  •  

Domanda


Edit:

I was looking at this ../ differently and was attaching ../ mentally with an idea of a directory path with a directory slash already (so directory name + / + ../) , which would point one directory too far back, but now I see that with directory name + ../ is actually correct in this case.


I'm unable to get a correct relative path between two files, only when one path is a file and the other a directory, is this normal expected behavior with Path.relativize(Path)? JavaDocs mention that it works with Path objects, but nothing more specific than that.

Here's my example code (running on Windows), which contains comments on what I expected the output to be:

import java.nio.file.Path;
import java.nio.file.Paths;
public class PathsTest
{
    public static void main(String[] args)
    {
        Path pathA = Paths.get("C:\\a\\b\\1.txt");
        System.out.println(pathA);
        Path pathB = Paths.get("C:\\a\\b\\2.txt");
        System.out.println(pathB);
        Path relativePathBetween = pathA.relativize(pathB);
        System.out.println("rel: " + relativePathBetween);
        // Outputs "..\2.txt" (for the last print here)
        // Expected: "2.txt"

        pathA = Paths.get("C:\\a\\b\\1.txt");
        pathA = pathA.getParent(); // Obtaining parent here, so C:\a\b
        System.out.println(pathA);
        pathB = Paths.get("C:\\a\\b\\2.txt");
        System.out.println(pathB);
        relativePathBetween = pathA.relativize(pathB);
        System.out.println("rel: " + relativePathBetween);
        // Outputs: "2.txt"
        // Expected: "2.txt"

        // So why does pathA have to be a directory and not a file?
        // Javadocs don't seem to mention that.
    }
}

And here's the entire output from the program:

C:\a\b\1.txt
C:\a\b\2.txt
rel: ..\2.txt
C:\a\b
C:\a\b\2.txt
rel: 2.txt
È stato utile?

Soluzione

../ means the parent, so in your first example it corresponds to "C:\\a\\b\\ and the result you get looks fine.

Why do you expect "2.txt", which you would get for Path pathB = Paths.get("C:\\a\\b\\1.txt\\2.txt");?

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top