JDK 12’s Files.mismatch Method
JDK 12 introduces a new method to the Files class. The method, Files.mismatch(Path,Path), has been introduced to JDK 12 via JDK-8202302 and is available in JDK 12 Early Access Build 20 (same early access build that supports the new {@systemProperty} Javadoc tag).
JDK-8202302 [“(fs) New Files.mismatch method for comparing files”] adds the Files.mismatch(Path,Path) method “to compare the contents of two files to determine whether there is a mismatch between them” and can be used to determine “whether two files are equal.” There was talk at one time of adding a Files.isSameContent() method, but it was decided to use Files.mismatch(Path,Parh) because of its consistency “with the Arrays.mismatch and Buffer.mismatch methods.”
The next code listing contains a simple Java class that demonstrates the new Files.mismatch(Path,Path) and contrasts it with Files.isSameFile(Path,Path).
package dustin.examples.jdk12.files;
import java.nio.file.Files;
import java.nio.file.Path;
import static java.lang.System.out;
/**
* Demonstrate {@code Files.mismatch(Path,Path)} introduced with JDK 12
* and useful for determining if two files have the same content even
* if they're not the same files.
*/
public class FilesDemo
{
public static void main(final String[] arguments) throws Exception
{
if (arguments.length < 2)
{
out.println("USAGE: FilesDemo <file1Name> <file2Name>");
return;
}
final String file1Name = arguments[0];
final Path file1Path = Path.of(file1Name);
final String file2Name = arguments[1];
final Path file2Path = Path.of(file2Name);
out.println("\nFiles '" + file1Name + "' and '" + file2Name + "' are "
+ (Files.isSameFile(file1Path, file2Path) ? "the" : "NOT the")
+ " same.\n\n");
out.println("\nFiles '" + file1Name + "' and '" + file2Name + "' are "
+ (Files.mismatch(file1Path, file2Path) == -1 ? "the" : "NOT the")
+ " same content.\n\n");
}
}When the above code is executed against various combinations of files, it provides results captured in the next table.
| Files Relationship | Files.isSameFile(Path,Path) | Files.mismatch(Path,Path) |
|---|---|---|
| Same File | true | true |
| Copied File | false | true |
| Different Files | false | false |
| Soft-linked | true | true |
| Hard-linked | true | true |
The addition of Files.mismatch(Path,Path) is another step in accomplishing JDK-6852033 [“Inputs/Outputs methods to make common I/O tasks easy to do”] and makes it easier to determine when two files that are not the same file are still “equal” or have the same content.
| Published on Java Code Geeks with permission by Dustin Marx, partner at our JCG program. See the original article here: JDK 12’s Files.mismatch Method Opinions expressed by Java Code Geeks contributors are their own. |

