java之IO流运用—文件内容提取至ArrayList

java之IO流运用—文件内容提取至ArrayList

有以下交易明细:

客户号  姓名  所述机构号  性别  帐号  发生时间  发生金额

000001|刘德华|0000|1|4155990188888888|2006/07/20 20:00:05|300.00
000201|郭富城|0002|1|4155990199999999|2006/07/20 20:00:05|500.00
000101|黄晓明|0012|1|4155990100000000|2006/07/20 20:00:05|1000.50
000101|张东健|0012|1|4155990155555555|2006/07/20 20:00:05|600.99
000301|迪丽热巴|0013|0|4155990111111111|2006/07/22 20:10:05|5000.00
004002|张学友|0000|1|4155990188888888|2006/07/25 20:00:05|200.00

一行是一条交易明细,每行分6列,列间用|分隔。#为注释符号。类TransRecord存储一条明细(金额字段数据类型定为BigDecimal)。解析文件数据至List

这个实例中的信息全部在“record.txt”文件中存储,需要将文本数据解析为6个交易记录对象并存入ArrayList中,首先需要使用FileInputStream获取文件输入流,然后将每行文本数据解析为一个交易记录对象,将每个对象添加到数组中,接下来便可对数组进行操作,按照客户号查询记录,按照日期段查询记录,计算总交易金额,按照交易金额排序

分析

要实现上述功能,需创建三个类:

  • TransRecord类:交易记录类,定义交易记录的属性,并重写hashCode和equals,重写toString方法
  • TransRecordManager类:交易记录管理类,声明所有方法并实现
  • TestTransRecord类:测试类,程序主入口

代码如下:

TransRecord类

import java.math.BigDecimal;
import java.util.Date;
/**
 * 交易记录类
 * @author max
 *
 */
public class TransRecord {
	/**客户号*/
	private String num;
	/**姓名*/
	private String name;
	/**机构号*/
	private String jnum;
	/**性别*/
	private String sex;
	/**账号*/
	private String account;
	/**发生时间*/
	private Date time;
	/**发生金额*/
	private BigDecimal cash;
	
	public TransRecord() {
		// TODO Auto-generated constructor stub
	}
	
	
	public TransRecord(String num, String name, String jnum, String sex, String account, Date time, BigDecimal cash) {
		super();
		this.num = num;
		this.name = name;
		this.jnum = jnum;
		this.sex = sex;
		this.account = account;
		this.time = time;
		this.cash = cash;
	}


	public String getNum() {
		return num;
	}
	public void setNum(String num) {
		this.num = num;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getJnum() {
		return jnum;
	}
	public void setJnum(String jnum) {
		this.jnum = jnum;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	public String getAccount() {
		return account;
	}
	public void setAccount(String account) {
		this.account = account;
	}
	public Date getTime() {
		return time;
	}
	public void setTime(Date time) {
		this.time = time;
	}
	public BigDecimal getCash() {
		return cash;
	}
	public void setCash(BigDecimal cash) {
		this.cash = cash;
	}


	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((account == null) ? 0 : account.hashCode());
		result = prime * result + ((cash == null) ? 0 : cash.hashCode());
		result = prime * result + ((jnum == null) ? 0 : jnum.hashCode());
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		result = prime * result + ((num == null) ? 0 : num.hashCode());
		result = prime * result + ((sex == null) ? 0 : sex.hashCode());
		result = prime * result + ((time == null) ? 0 : time.hashCode());
		return result;
	}


	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		TransRecord other = (TransRecord) obj;
		if (account == null) {
			if (other.account != null)
				return false;
		} else if (!account.equals(other.account))
			return false;
		if (cash == null) {
			if (other.cash != null)
				return false;
		} else if (!cash.equals(other.cash))
			return false;
		if (jnum == null) {
			if (other.jnum != null)
				return false;
		} else if (!jnum.equals(other.jnum))
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		if (num == null) {
			if (other.num != null)
				return false;
		} else if (!num.equals(other.num))
			return false;
		if (sex == null) {
			if (other.sex != null)
				return false;
		} else if (!sex.equals(other.sex))
			return false;
		if (time == null) {
			if (other.time != null)
				return false;
		} else if (!time.equals(other.time))
			return false;
		return true;
	}


	@Override
	public String toString() {
		return "TransRecord [num=" + num + ", name=" + name + ", jnum=" + jnum + ", sex=" + sex + ", account=" + account
				+ ", time=" + time + ", cash=" + cash + "]";
	}

}

TransRecordManager类

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 交易记录类
 * @author max
 *
 */
public class TransRecordManager {

	// 声明成员变量用于存储所有的交易记录数据
	private List records = new ArrayList<>();

	/**
	 * 加载数据
	 * 
	 * @param in - 数据流
	 * @return
	 * @throws - 解析过程中IO错误
	 */
	public void load(InputStream in) throws IOException {
		// 将获取的字节流转换为字符流并包装成缓冲流
		BufferedReader br = new BufferedReader(new InputStreamReader(in));
		String line = "";
		while ((line = br.readLine()) != null) {
			// 排除注释行(以"#"开头)
			if (!line.startsWith("#")) {
				TransRecord record = parseDateToObj(line);
				records.add(record);
			}
		}
	}

	/**
	 * 将一行文本数据解析为一个交易记录对象
	 * @param line
	 * @return
	 */
	private TransRecord parseDateToObj(String line) {
		TransRecord tr = new TransRecord();
		String[] data = line.split("\\|");
		tr.setNum(data[0]);
		tr.setName(data[1]);
		tr.setJnum(data[2]);
		tr.setSex(Objects.equals(data[3], "1") ? "男" : "女");
		tr.setAccount(data[4]);
		tr.setCash(new BigDecimal(data[6]));
		try {
			DateFormat fmt = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
			Date time = fmt.parse(data[5]);
			tr.setTime(time);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return tr;
	}

	/**
	 * 加载数据
	 * @param fileName - 包含记录数据的文件名
	 * @return
	 * @throws - 解析过程中IO错误
	 */
	public void load(String fileName) throws IOException {
		File f = new File(fileName);
		InputStream is = new FileInputStream(f);
		load(is);
	}

	/**
	 * 取所有记录
	 * @return 所有记录数组或null
	 */
	public List getAll() {
		return records;
	}

	/**
	 * 按客户号查询记录
	 * 
	 * @param customerNumber - 客户号
	 * @return 符合条件的记录数组或null
	 */
	public List findByCustomerNumber(String customerNumber) {
		return records.stream().filter(r -> Objects.equals(r.getNum(), customerNumber)).collect(Collectors.toList());
	}

	/**
	 * 按日期段查询记录
	 * @param start - 开始日期
	 * @param end   - 结束日期
	 * @return 符合条件的记录数组或null
	 */
	public List findByDate(String start, String end) {
		try {
			DateFormat fmt = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
			long from = fmt.parse(start).getTime();
			long to = fmt.parse(end).getTime();

//			List list = new ArrayList<>();
//			for (TransRecord tr : records) {
//				long now = tr.getTime().getTime();
//				if (now >= from && now <= to) {
//					list.add(tr);
//				}
//			}
//			return  list;
			
			//流式API写法
			return records.stream()
						.filter(r->{
						long now = r.getTime().getTime();
						return now>= from && now <= to;
					})
					.collect(Collectors.toList());
			
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 取得总金额
	 * @return 总金额
	 */
	public BigDecimal totalAmount() {
		BigDecimal result = new BigDecimal(0);
		for(TransRecord tr : records) {
			BigDecimal cash = tr.getCash();
			result = result.add(cash);
		}
		return result;
	}

	/**
	 * 按金额排序
	 * @return 按金额升序排序的结果
	 */
	public List sortByAmount() {
		Collections.sort(records,(r1,r2)->r1.getCash().compareTo(r2.getCash()));
		return records;
	}

	/**
	 * 打印
	 * @param out - 输出流
	 */
	public void print(OutputStream out) {
		
	}

}

TestTransRecord类

import java.io.IOException;
import java.util.List;
/**
 * 有以下交易明细:
#客户号 姓名 所述机构号 性别 帐号 发生时间 发生额
000001|刘德华|0000|1|4155990188888888|2006/07/20 20:00:05|300.00
000201|郭富城|0002|1|4155990199999999|2006/07/20 20:00:05|500.00
000101|黄晓明|0012|1|4155990100000000|2006/07/20 20:00:05|1000.50
000101|张东健|0012|1|4155990155555555|2006/07/20 20:00:05|600.99
000301|迪丽热巴|0013|0|4155990111111111|2006/07/22 20:10:05|5000.00
004002|张学友|0000|1|4155990188888888|2006/07/25 20:00:05|200.00

一行是一条交易明细,每行分6列,列间用|分隔。#为注释符号。
类TransRecord存储一条明细(金额字段数据类型定为BigDecimal)。
解析文件数据至List\。
 * @author max
 *
 */
public class TestTransRecord {
	public static void main(String[] args) throws IOException {
		TransRecordManager trm = new TransRecordManager();
		trm.load("src/record.txt");
		//查询所有
		for(TransRecord tr : trm.getAll()) {
			System.out.println(tr);
		}
		System.out.println("============================");
		//根据客户号查询
		List list = trm.findByCustomerNumber("000001");
		for(TransRecord tr : list) {
			System.out.println(tr);
		}
		System.out.println("============================");
		//查询指定日期之间的记录
		trm.findByDate("2006/07/20 00:00:00", "2006/07/22 00:00:00");
		for(TransRecord tr : list) {
			System.out.println(tr);
		}
		System.out.println("============================");
		//获取交易总金额
		System.out.println(trm.totalAmount());
		System.out.println("============================");
		//根据交易金额升序排序
		list = trm.sortByAmount();
		for(TransRecord tr : list) {
			System.out.println(tr);
		}
	}

}

测试结果如下:

java之IO流运用—文件内容提取至ArrayList_第1张图片

你可能感兴趣的:(java高级)