java代码没错 报错,!java文件排序代码报错,改了两天了,都没有解决!

求助!java文件排序代码报错,改了两天了,都没有解决!!

本帖最后由 yds27 于 2014-04-23 16:49:03 编辑

java代码报错:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0

at it.heber.sandbox.FileComperator2.first(FileComperator2.java:80)

at it.heber.sandbox.FileComperator2.getFileId(FileComperator2.java:56)

at it.heber.sandbox.FileComperator2.access$0(FileComperator2.java:55)

at it.heber.sandbox.FileComperator2$1.compare(FileComperator2.java:33)

at it.heber.sandbox.FileComperator2$1.compare(FileComperator2.java:1)

at java.util.TimSort.countRunAndMakeAscending(Unknown Source)

at java.util.TimSort.sort(Unknown Source)

at java.util.TimSort.sort(Unknown Source)

at java.util.Arrays.sort(Unknown Source)

at it.heber.sandbox.FileComperator2.sortFilesByIdName(FileComperator2.java:39)

at it.heber.sandbox.FileComperator2.main(FileComperator2.java:17)

具体代码

package it.heber.sandbox;

import java.io.File;

import java.util.Arrays;

import java.util.Comparator;

import java.util.Date;

public class FileComperator2 {

private static File[] images;

public static void main(String[] args) {

File folder = new File("e:\\q");//1.txt,2.txt,3.txt     一共三个文件

images = folder.listFiles();

sortFilesByIdName(true);

}

/**

* Function sorts files by their Id on the end of the file name.

* (e.q. img_1.png, img_2.png, ...)

*

* @param sortAsc sorting Flag [true=ASC|false=DESC]

*/

public static void sortFilesByIdName(final boolean sortAsc) {

Comparator comparator = new Comparator() {

@Override

public int compare(File o1, File o2) {

if (sortAsc) {

return getFileId(o1).compareTo(getFileId(o2));

} else {

return -1 * getFileId(o1).compareTo(getFileId(o2));

}

}

};

Arrays.sort(images, comparator);

System.out.println("###n### Sort file by Id in file name ######");

for (File image : images) {

System.out.println(image.getName() + "t" +

new Date(image.lastModified()));

}

}

/**

* Helper method to determine file Id for sorting. File name has following

* structure: img_11.png

*

* @param file

* @return

*/

private static Integer getFileId(File file) {

String fileName = first(file.getName().split("."));

String fileId = last(fileName.split("_"));

return Integer.parseInt(fileId);

}

/**

* Generic helper methode to get the last field of an array

*

* @param  Array type

* @param array Array with elements

* @return last field of an array

*/

private static  T last(T[] array) {

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值