例子
以下示例显示java.io.File.compareTo(File pathname)方法的用法。
package com.jc2182;
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();
}
}
}
让我们编译并运行以上程序,这将产生以下结果-
Lexicographically, abstract path name test.txt > abstract path name File/test1.txt
Value returned: 46