LF398编程问题
作者:Judy发布时间:2023-02-10浏览:458
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public class ListFile {
Map<String,Long> map = new HashMap<String, Long>();//存放文件信息,key 为文件名,value为文件大小
public void getDir(String strPath) throws Exception {
try {
File f = new File(strPath);
if (f.isDirectory()) {
File[] fList = f.listFiles();
for (int j = 0; j < fList.length; j++) {
if (fList[j].isDirectory()) {
getDir(fList[j].getPath()); // 在getDir函数里面又调用了getDir函数本身
} else if (fList[j].isFile()) {
map.put(fList[j].getPath(), fList[j].length());//将文件放入map
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
//对文件进行排序
public List<Map.Entry<String, Long>> sortFile() {
List<Map.Entry<String, Long>> list = new ArrayList<Map.Entry<String, Long>>(map.entrySet());
ValueComparator vc = new ValueComparator();
Collections.sort(list,vc);
return list;
}
public static void main(String[] args) {
String strPath = "D:";
ListFile lf = new ListFile();
try {
lf.getDir(strPath);
List<Map.Entry<String, Long>> list = lf.sortFile();
for (Entry<String, Long> entry : list) {
System.out.println(entry.getKey() + " " +entry.getValue() + "字节");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
class ValueComparator implements Comparator<Map.Entry<String, Long>> {
public int compare(Map.Entry<String, Long> o1, Map.Entry<String, Long> o2) {
return (int) (o1.getValue() - o2.getValue());//这是升序,降序为:o2.getValue() - o1.getValue()
}
}
另外,团IDC网上有许多产品团购,便宜有口碑