map 数据筛选和排序

sfit0144 (李四) 2015-01-10 18:00:25
1
Sfit0734 (Sfit0734) 2015-01-10 18:00:38
go home
sfit0144 (李四) 2015-01-10 18:09:52
下班
261340 (叶在宗) 2015-01-10 18:10:05
图片: {5F4C20B4-134F-4014-801D-8FFBA58587E9}.png
sfit0513 (蒋大有) 2015-01-10 18:43:55
下班
sfit0122 (雷一果) 2015-01-10 19:06:16
下班

将上面数据分析成下面格式,上面数据也是存在于文件当中,下面数据也是分析完后最后也放在文件当中

打卡日期    姓名      上班打卡             下班打卡             
2015-01-10  何科                           2015-01-10 19:46:05
2015-01-10  刘俊                           2015-01-10 20:39:00
2015-01-10  匡磊                           2015-01-10 19:43:52
2015-01-10  叶在宗                         2015-01-10 18:10:05
2015-01-10  李四      2015-01-10 18:00:25  2015-01-10 18:09:52
2015-01-10  蒋大有                         2015-01-10 18:43:55
2015-01-10  雷一果                         2015-01-10 19:06:16
2015-01-13  何科      2015-01-13 09:22:58  2015-01-13 19:01:07
2015-01-13  刘俊      2015-01-13 09:26:34  2015-01-13 19:28:37

下面是代码:
public class MessageHistory {

	Map<String, MessageSenderInfo> lines = new HashMap<String, MessageSenderInfo>();
	String outputPath;
	public static void main(String[] args) {
		MessageHistory messageHistory = new MessageHistory();
		messageHistory.multiReadMessage();
		messageHistory.outputCardRecordsToFile();
	}
	
	public MessageHistory() {
		outputPath = System.getProperty("user.dir")+File.separator+formatDate(new Date()) + "—打卡记录.txt";
		File f = new File(outputPath);
		if(f.exists()){
			f.delete();
		}
	}

	
	/**
	 * 消息文件以work开头
	 * 读取文件
	 */
	public void multiReadMessage(){
		File dir = new File(System.getProperty("user.dir"));
		if(dir.getParentFile().exists()){
			for(File file:dir.listFiles()){
				if(file.getName().trim().matches("^work.*\\.txt$")){
					System.out.println("start read "+file.getAbsolutePath());
					readMessage(file.getAbsolutePath());
				}
			}
		}
	}

	public void lineToMap(String line) {
		if (line.matches("^[A-Za-z0-9]{6}.*")) {
			int index = line.indexOf("(");
			int lastIndex = line.lastIndexOf(")");
			if (index > 0 && lastIndex > 0) {
				String workCode = line.substring(0, index);
				String name = line.substring(index + 1, lastIndex);
				String dateStr = line.substring(lastIndex + 1).trim();
				Date date = parseDate(dateStr);
				String key = formatDate(date) + "--" + workCode;
				MessageSenderInfo recoderBean = lines.get(key);
				if (recoderBean == null) {
					recoderBean = new MessageSenderInfo(workCode, name);
					recoderBean.setAtWorkTime(date);
				} else {
					if (recoderBean.getOffWorkTime() == null) {
						recoderBean.setOffWorkTime(date);
					}else{
						if(date.getTime() < recoderBean.getAtWorkTime().getTime()){
							recoderBean.setAtWorkTime(date);
						}else if(date.getTime() > recoderBean.getOffWorkTime().getTime()){
							recoderBean.setOffWorkTime(date);
						}
					}

				}
				lines.put(key, recoderBean);
			}
		}
	}

	public List<Map.Entry<String,MessageSenderInfo>> sortMessage(){
		List<Map.Entry<String,MessageSenderInfo>> list = new ArrayList<Map.Entry<String,MessageSenderInfo>>(lines.entrySet());
		Collections.sort(list, new MessageComparator());
		return  list;
	}
	/**
	 * 输出到文件
	 */
	public void outputCardRecordsToFile() {
		printHeader();
		System.out.println("总记录:"+lines.size());
		List<Map.Entry<String,MessageSenderInfo>> list = sortMessage();
		for (Map.Entry<String, MessageSenderInfo> e : list) {
			MessageSenderInfo messageSenderInfo = e.getValue();
			String line = formatDate(messageSenderInfo.getAtWorkTime()) + "  "+
					formatStringLen(messageSenderInfo.getName(),8) + "  " ;
			if(messageSenderInfo.getOffWorkTime() == null){
				if(getHour(messageSenderInfo.getAtWorkTime()) >= 12){
					line += formatStringLen("",21);
				}
				line+=formatLongDate(messageSenderInfo.getAtWorkTime());
			}else
			if(messageSenderInfo.getOffWorkTime() != null){
				line += formatLongDate(messageSenderInfo.getAtWorkTime()) + "  " ;
				line+=formatLongDate(messageSenderInfo.getOffWorkTime());
			}
			writeLine(outputPath, line);
		}
	}
	/**
	 * 打印头部
	 */
	public void printHeader(){
		String line = formatStringLen("打卡日期",12)+
		formatStringLen("姓名",10)+
		formatStringLen("上班打卡",21)+
		formatStringLen("下班打卡",21);
		writeLine(outputPath, line);
	}
	
	/**
	 * 格式化字符串长度
	 * @param s
	 * @param len
	 * @return
	 */
	public String formatStringLen(String s, int len) {
		if (len > s.getBytes().length) {
			StringBuilder sBuilder = new StringBuilder(s);
			for (int i = 0; i < len - s.getBytes().length; i++) {
				sBuilder.append(" ");
			}
			return sBuilder.toString();
		}
		return s;
	}
	
	public void writeLine(String path, String s) {
		File f = new File(path);
		OutputStream os = null;
		try {
			os = new FileOutputStream(f, true);
			Writer wirte = new OutputStreamWriter(os, "UTF-8");
			BufferedWriter bufferedWriter = new BufferedWriter(wirte);
			bufferedWriter.write(s);
			bufferedWriter.newLine();
			bufferedWriter.flush();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (os != null) {
				try {
					os.close();
					os = null;
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
	
	public void readMessage(String path) {
		InputStream ins = null;
		BufferedReader buf = null;
		try {
			ins = new FileInputStream(path);
			buf = new BufferedReader(new InputStreamReader(ins, codeString(path)));
			String line = null;
			while ((line = buf.readLine()) != null) {
				lineToMap(line.trim());
			}
		} catch (FileNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (ins != null) {
				try {
					ins.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
	
	/**
	 * 排序比较
	 * @author sfit0734
	 *
	 */
	class MessageComparator implements Comparator<Map.Entry<String,MessageSenderInfo>> {
		@Override
		public int compare(Map.Entry<String,MessageSenderInfo> e1, Map.Entry<String,MessageSenderInfo> e2) {
			MessageSenderInfo m1 = e1.getValue();
			MessageSenderInfo m2 = e2.getValue();
			String dateStr = formatDate(m1.getAtWorkTime());
			String dateStr1 = formatDate(m2.getAtWorkTime());
			
			int result =  dateStr.compareTo(dateStr1);
			if(result != 0){
				return result;
			}else{
				return m1.getName().compareTo(m2.getName());
			}
		}
	};


	public Date parseDate(String dataStr) {
		DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		//String dateString = formatter.format(currentTime);
		Date date = null;
		try {
			date = formatter.parse(dataStr);
		} catch (ParseException e) {

			e.printStackTrace();
		}
		return date;
	}

	public String formatDate(Date date) {
		DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		String dateString = formatter.format(date);
		
		return dateString;
	}

	public String formatLongDate(Date date) {
		DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String dateString = formatter.format(date);
		
		return dateString;
	}
	/**
	 * 获取小时
	 * @param d
	 * @return
	 */
	public int getHour(Date d){
		Calendar cal=Calendar.getInstance();
		cal.setTime(d);
		
		return cal.get(Calendar.HOUR_OF_DAY);
	}
	
    /** 
     * 判断文件的编码格式 
     * @param fileName :file 
     * @return 文件编码格式 
     * @throws IOException 
     * @throws Exception 
     */  
    public  String codeString(String fileName) throws IOException {  
        BufferedInputStream bin = new BufferedInputStream(  
        new FileInputStream(fileName));  
        int p = (bin.read() << 8) + bin.read();  
        String code = null;  
          
        switch (p) {  
            case 0xefbb:  
                code = "UTF-8";  
                break;  
            case 0xfffe:  
                code = "Unicode";  
                break;  
            case 0xfeff:  
                code = "UTF-16BE";  
                break;  
            default:  
                code = "GBK";  
        }  
          
        return code;  
    }  
    
	class MessageSenderInfo {
		String workCode;
		String name;
		Date atWorkTime;
		Date offWorkTime;

		public MessageSenderInfo() {
			super();
			// TODO Auto-generated constructor stub
		}

		public MessageSenderInfo(String workCode, String name) {
			super();
			this.workCode = workCode;
			this.name = name;

		}

		public String getWorkCode() {
			return workCode;
		}

		public void setWorkCode(String workCode) {
			this.workCode = workCode;
		}

		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}

		public Date getAtWorkTime() {
			return atWorkTime;
		}

		public void setAtWorkTime(Date atWorkTime) {
			this.atWorkTime = atWorkTime;
		}

		public Date getOffWorkTime() {
			return offWorkTime;
		}

		public void setOffWorkTime(Date offWorkTime) {
			this.offWorkTime = offWorkTime;
		}
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值