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

(全文完)

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