Java.io.File.compareTo() Method

Advertisements


Description

The java.io.File.compareTo(File pathname) method compares two abstract pathnames lexicographically. The ordering defined by this method is dependent upon the operating system

Declaration

Following is the declaration for java.io.File.compareTo(File pathname) method:

public int compareTo(File pathname)

Parameters

  • pathname -- The abstract pathname to be compared to the this abstract pathname.

Return Value

This method returns Zero if the argument is equal to this abstract pathname, negative value and a value greater than 0 if the abstract pathname is lexicographically less than the argument and greater than the argument respectively.

Exception

  • NA

Example

The following example shows the usage of java.io.File.compareTo(File pathname) method.

package com.tutorialspoint;

import java.io.File;

public class FileDemo {
   public static void main(String[] args) {
      
      File f = null;
      File f1 = null;
      
      try{
         // create new files
         f = new File("test.txt");
         f1 = new File("File/test1.txt");
         
         // returns integer value
         int value = f.compareTo(f1);
         
         // prints
         System.out.print("Lexicographically, ");
         System.out.print("abstract path name test.txt");
         
         // if lexicographically, argument = abstract path name
         if(value == 0)
         {
            System.out.print(" = ");
         }
         
         // if lexicographically, argument < abstract path name
         else if(value > 0)
         {
            System.out.print(" > ");
         }
         
         // if lexicographically, the argument > abstract path name
         else
         {
            System.out.print(" < ");
         }
         
         // print
         System.out.println("abstract path name File/test1.txt");
         
         // prints the value returned by compareTo()
         System.out.print("Value returned: "+value);
         
      }catch(Exception e){
         e.printStackTrace();
      }
   }
}

Let us compile and run the above program, this will produce the following result:

Lexicographically, abstract path name test.txt > abstract path name File/test1.txt
Value returned: 14



Advertisements
Advertisements