并不是说不要创建实体,而是有时并没必要创建
例如:从磁盘上读取文件在页面上显示,磁盘上得文件名字是201101.xls,那么在页面上显示时,需要显示2011年1月
我们做法是:先读取出文件保存在list中,但是文件名转换如何做呢?
通常可以创建个file实体,里面两个字段,name_file,name_show
但是我们还可以通过map来实现
原理,采用json的数据格式 [name_file:201101.xls,name_show:2011年1月]
class BusinessTypeSumReportAction{
public static List getFiles(String dirname) throws Exception {
List file_names = null;
File dir = new File(dirname);
if (dir.exists()) {
file_names = new ArrayList();
File[] files = dir.listFiles();
// 排序
Arrays.sort(files,
new BusinessTypeSumReportAction.CompratorByLastModified());
for (int i = 0; i < files.length; i++) {
String filename = files[i].getName();
if (filename.matches("^.+\\.xls$")&&filename.matches("2[0-9]{5}+\\.xls$")) {
Map<String, String> map = new HashMap<String, String>();
String year = filename.substring(0, 4)+"年";
String month = filename.substring(4,6)+"月";
if(month.startsWith("0"))month = month.substring(1,3);
map.put("name_file", files[i].getName());
map.put("name_show", year+month);
file_names.add(map);
}
}
} else {
System.out.println("该目录没有任何文件信息!");
}
return file_names;
}
public static List<Map<String, List>> getFiles2(String dirname)
throws Exception {
List file_names = null;
List<Map<String, List>> listMap = new ArrayList<Map<String, List>>();
Map<String, List> map = new HashMap<String, List>();
File dir = new File(dirname);
String tempyear = "";
String year = "";
if (dir.exists()) {
file_names = new ArrayList();
File[] files = dir.listFiles();
// 排序
Arrays.sort(files,
new BusinessTypeSumReportAction.CompratorByLastModified());
for (int i = 0; i < files.length; i++) {
// 取出文件名年份,同一年份的封装到一个list中,数据结构为json类似
String filename = files[i].getName();
if (filename.matches("^.+\\.xls$")) {
year = filename.substring(0, 5);
file_names.add(files[i].getName());
if (!tempyear.equals(year)) {
map.put(year, file_names);
}
tempyear = year;
}
}
} else {
System.out.println("该目录没有任何文件信息!");
}
return file_names;
}
private static String format(String format, Date date) {
SimpleDateFormat dateFormat = new SimpleDateFormat(format);
return dateFormat.format(date);
}
private static class CompratorByLastModified implements Comparator<File> {
public int compare(File f1, File f2) {
long diff = f1.lastModified() - f2.lastModified();
if (diff > 0)
return 1;
else if (diff == 0)
return 0;
else
return -1;
}
public boolean equals(Object obj) {
return true;
}
}
}