JAVA:文件按名称排序,文件夹在前,文件在后

实现Comparator接口

源码如下:

package data;

import java.io.File;
import java.util.Comparator;

/**
 * @Title: Comparator.java
 * @Package: data
 * @Description: Comparator:Directory>File
 * @author: TRXCX-JZX
 * @date: 2021年11月21日-上午10:52:52
 */
public class FileComparator implements Comparator {
	public int compare(File file1, File file2) {
		int value1 = 0, value2 = 0;
		if (file1.isDirectory()) {
			value1 = 1;
		}
		if (file2.isDirectory()) {
			value2 = 1;
		}
		if (value1 != value2) {
			return value2 - value1;
		} else {
			return file1.getName().compareTo(file2.getName());
		}
	}
}

调用如下:

directories是File数组

Arrays.sort(directories, 0, directories.length, new FileComparator());

你可能感兴趣的:(java,开发语言)