技巧:当不能抛出异常时
2010-05-04 00:00:00 来源:WEB开发网清单 4. 先读取,然后排序
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
public class FileComparator {
private static ArrayList<String> getCanonicalPaths(ArrayList<File> files)
throws IOException {
ArrayList<String> paths = new ArrayList<String>();
for (File file : files) paths.add(file.getCanonicalPath());
return paths;
}
public static void main(String[] args) throws IOException {
ArrayList<File> files = new ArrayList<File>();
for (String arg : args) {
files.add(new File(arg));
}
ArrayList<String> paths = getCanonicalPaths(files);
// to maintain the original mapping
HashMap<String, File> map = new HashMap<String, File>();
int i = 0;
for (String path : paths) {
map.put(path, files.get(i));
i++;
}
Collections.sort(paths);
files.clear();
for (String path : paths) {
files.add(map.get(path));
}
}
}
赞助商链接