Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Ganesh_JavaSE7_Programming_1z0-804_study_guide.pdf
Скачиваний:
94
Добавлен:
02.02.2015
Размер:
5.88 Mб
Скачать

chapter 9 Java File I/O (NIO.2)

Comparing Two Paths

The Path interface provides two methods to compare two Path objects: equals() and compareTo(). The equals() method checks the equality of two Path objects and returns a Boolean value when compareTo() compares two Path objects character by character and returns an integer: 0 if both Path objects are equal; a negative integer if this path is lexicographically less than the parameter path; and a positive integer if this path is lexicographically greater than the parameter path.

Listing 9-3 contains a small program to understand these methods.

Listing 9-3.  PathCompare1.java

import java.nio.file.*;

// illustrates how to use compareTo and equals and also shows the difference between the two methods class PathCompare1 {

public static void main(String[] args) { Path path1 = Paths.get("Test");

Path path2 = Paths.get("D:\\OCPJP7\\programs\\NIO2\\Test"); // comparing two paths using compareTo() method

System.out.println("(path1.compareTo(path2) == 0) is: " + (path1.compareTo(path2) == 0));

//comparing two paths using equals() method System.out.println("path1.equals(path2) is: " + path1.equals(path2));

// comparing two paths using equals() method with absolute path System.out.println("path2.equals(path1.toAbsolutePath()) is "

+ path2.equals(path1.toAbsolutePath()));

}

}

Intentionally, we have taken one path as relative path and another one as absolute path. Can you guess the output of the program? It printed the following:

(path1.compareTo(path2) == 0) is: false path1.equals(path2) is: false path2.equals(path1.toAbsolutePath()) is true

Let’s understand the program step by step.

You first compare two paths using the compareTo() method, which compares paths character by character and returns an integer. In this case, since one path is a relative path and another one is an absolute path, it is expected to get first a message that says both paths are not equal.

Then you compare both paths using equals(). The result is the same, which means even if two Path objects are pointing to the same file/directory, it is possible that equals() returns false. You need to make sure that both paths are absolute paths.

In the next step, you convert the relative path to an absolute path and then compare them using equals(). This time both paths match.

257

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]