Java编程根据文件名排序

声明:欢迎批评指正

目标:实现文件名排序,文件名是汉字、字母、数字混排

前言:项目要实现文件名排序,网上很多混排文件名的方法需要引入PINYIN包,写的也很复杂,自己研究了下,发现了一个简单的方法,经过测试可以使用,大家也可以测试一下,看是不是简单有效

测试环境:eclipse javaee Version: 2018-09 (4.9.0)/jdk8/windows

准备工作:

一、api准备:

int java.io.File.compareTo(File pathname)

java File类的compareTo方法

Compares two abstract pathnames lexicographically. The ordering defined by this method depends upon the underlying system. On UNIX systems, alphabetic case is significant in comparing pathnames; on Microsoft Windows systems it is not.

按字典顺序比较两个路径名。此方法顺序依赖于底层系统。在UNIX系统中,字母比较中是有意义的,windows中不是。

Specified by: compareTo(...) in Comparable

Parameters:

pathname The abstract pathname to be compared to this abstract pathname

Returns:

Zero if the argument is equal to this abstract pathname, a value less than zero if this abstract pathname is lexicographically less than the argument, or a value greater than zero if this abstract pathname is lexicographically greater than the argument

0表示路径名一样,负数表示字典顺序小,正数表示字典顺序大。

Since:

1.2

 

<File> void java.util.Arrays.sort(File[] a, Comparator<? super File> c)

 

二、文件准备:

在windows的d盘中建立一个“测试”文件夹,在其下建立七个文件,结构如下:

D:\测试
├─a香蕉1
├─b苹果3
├─Z苹果1
├─桔子1
├─桔子2
├─苹果1
└─苹果2

三、项目准备:

在eclipse中新建一个java项目,定义一个包含main方法的类FileOrder

 

正文:

package com.file.fileorder;

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

public class FileOrder {

	public static void main(String[] args) {
		File dir = new File("D:\\测试");
		File[] files = dir.listFiles();
		Arrays.sort(files, new Comparator<File>() {

			@Override
			public int compare(File f1, File f2) {
				return f1.compareTo(f2);
			}

		});
		for (File f : files) {
			System.out.println(f.getName());
		}
	}

}

排序结果如下:

a香蕉1
b苹果3
Z苹果1
桔子1
桔子2
苹果1
苹果2

(全文完)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章