001 /* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017 package org.apache.commons.io.comparator; 018 019 import java.io.File; 020 import java.io.Serializable; 021 import java.util.Comparator; 022 023 /** 024 * Compare two files using the {@link File#isDirectory()} method. 025 * <p> 026 * This comparator can be used to sort lists or arrays by directories and files. 027 * <p> 028 * Example of sorting a list of files/directories using the 029 * {@link #DIRECTORY_COMPARATOR} singleton instance: 030 * <pre> 031 * List<File> list = ... 032 * DirectoryFileComparator.DIRECTORY_COMPARATOR.sort(list); 033 * </pre> 034 * <p> 035 * Example of doing a <i>reverse</i> sort of an array of files/directories using the 036 * {@link #DIRECTORY_REVERSE} singleton instance: 037 * <pre> 038 * File[] array = ... 039 * DirectoryFileComparator.DIRECTORY_REVERSE.sort(array); 040 * </pre> 041 * <p> 042 * 043 * @version $Id: DirectoryFileComparator.java 1304052 2012-03-22 20:55:29Z ggregory $ 044 * @since 2.0 045 */ 046 public class DirectoryFileComparator extends AbstractFileComparator implements Serializable { 047 048 /** Singleton default comparator instance */ 049 public static final Comparator<File> DIRECTORY_COMPARATOR = new DirectoryFileComparator(); 050 051 /** Singleton reverse default comparator instance */ 052 public static final Comparator<File> DIRECTORY_REVERSE = new ReverseComparator(DIRECTORY_COMPARATOR); 053 054 /** 055 * Compare the two files using the {@link File#isDirectory()} method. 056 * 057 * @param file1 The first file to compare 058 * @param file2 The second file to compare 059 * @return the result of calling file1's 060 * {@link File#compareTo(File)} with file2 as the parameter. 061 */ 062 public int compare(File file1, File file2) { 063 return getType(file1) - getType(file2); 064 } 065 066 /** 067 * Convert type to numeric value. 068 * 069 * @param file The file 070 * @return 1 for directories and 2 for files 071 */ 072 private int getType(File file) { 073 if (file.isDirectory()) { 074 return 1; 075 } else { 076 return 2; 077 } 078 } 079 }