您的位置:首页 > 编程语言 > Java开发

CSV文件练手

2015-05-30 22:30 393 查看
首先创建两个注解,用于表示必填项和格式要求

package com.file.rrcl.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
* Date:2015/05/27
* @author dalin
*
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Comment {
String value();
}

package com.file.rrcl.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
* Date:2015/05/27
* @author dalin
*
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Required {
String type() default "String";
String regex() default "";
}
其次创建一个DTO

package com.file.rrcl.dto;

import com.file.rrcl.annotation.Comment;
import com.file.rrcl.annotation.Required;

public class TestDto {

// 账户名
@Required()
@Comment("账户名")
String accountno;

// 付款时间
@Comment("付款时间")
String accounttime;

// 交易时间
@Required(type = "Date", regex = "yyyy-MM-dd HH:mm:ss")
@Comment("交易时间")
String tradetime;

// 金额
@Required(type = "Float", regex = "^\\d+(\\.\\d+)?$")
@Comment("金额")
String amount;

public String getAccountno() {
return accountno;
}

public void setAccountno(String accountno) {
this.accountno = accountno;
}

public String getAccounttime() {
return accounttime;
}

public void setAccounttime(String accounttime) {
this.accounttime = accounttime;
}
}


最后,处理类:

package com.file.rrcl.biz;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.file.rrcl.annotation.Comment;
import com.file.rrcl.annotation.Required;
import com.file.rrcl.dto.TestDto;

public class MyCsvUtil {
private int CSV_COL_NUM = 4;

private List<String> fileRows = new ArrayList<String>();

/**
* Check the file format
*
* @param fileName
* @return
* @throws IOException
*/
public String checkFile(String fileName) throws IOException {
BufferedReader br = null;
BufferedWriter bw = null;

try {

br = new BufferedReader(new InputStreamReader(new FileInputStream(fileName),"gbk"));
String stemp;
while ((stemp = br.readLine()) != null) {
//				fileRows.add(stemp);
if(stemp != null && stemp.length() != 0){
fileRows.add(stemp);
}
}

if (fileRows != null && getColNum() == CSV_COL_NUM) {
String str = this.checkData();
System.out.println(str);
if (str != null && str.length() == 0){
bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("D:\\test\\订单发货ssssss.csv"),"gbk"));
for(String tmp:fileRows){
if(tmp != null && tmp.length() > 0){
bw.write(tmp);
bw.newLine();
}
bw.flush();
}
}

br.close();
bw.close();
return null;
}
if (fileRows.size() == 1) {
return "File is empty.";
} else if (getColNum() != 15) {
return "The number field is not 15, please check.";
} else {
return "File is empty.";
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
br.close();
}
if (bw != null) {
bw.close();
}
return null;
}
}

/**
* Check the data format
*
* @param fileName
* @return
*/
public String checkData() {
// Get Dto property
Class<TestDto> classDef = TestDto.class;
Field[] fields = classDef.getDeclaredFields();

// Get format sequence of DTO classes
Map<String, Field> tmpmap = new HashMap<String, Field>();
String dtoPropertyNODisplayName;
Field dtoField;
for (int i = 0; i < fields.length; i++) {
dtoField = fields[i];
dtoPropertyNODisplayName = dtoField.getAnnotation(Comment.class).value();
tmpmap.put(dtoPropertyNODisplayName.trim().toUpperCase(), dtoField);
}

//Get CSV file format sequence
List<Field> csvDataFormatlist = new ArrayList<Field>();
String[] firstRow = fileRows.get(0).toString().split(",");
Field field;
for (int i = 0; i < firstRow.length; i++) {
field = (Field) tmpmap.get(firstRow[i].trim().toUpperCase());
if(field == null){
return "File parsing Error";
}
csvDataFormatlist.add(field);
}

if (csvDataFormatlist == null || csvDataFormatlist.size() == 0) {
return "File parsing Error";
}

System.out.println("for(int row = 1;row < fileRows.size();row++){");
// The first column of the CSV file is the field name,so row = 1
for (int row = 1; row < fileRows.size(); row++) {
String[] cols = fileRows.get(row).toString().split(",");
if (cols.length != csvDataFormatlist.size()) {
return "File parsing Error";
}

for (int col = 0; col < getColNum(); col++) {
String str = cols[col];
System.out.print("Col:" + col + "Row:" + row);
System.out.print(str + " ");
this.checkFieldDataType(str, (Field) csvDataFormatlist.get(col));
}
System.out.println("");
}

return "";
}

public String checkFieldDataType(String value, Field field) {
boolean isRequired = field.isAnnotationPresent(Required.class);

if (isRequired) {
// Analyzing field format and format are consistent Dto
Required comment = field.getAnnotation(Required.class);
if (comment.type().equals("Date")) {
try {
SimpleDateFormat dateFormat = new SimpleDateFormat(comment.regex());
value = value.replaceAll("/", "-");
dateFormat.setLenient(false);
dateFormat.parse(value);

return "";
} catch (Exception e) {
System.out.print("Date format is wrong.");
System.out.print("");
return "Date format is wrong.";
}
} else if (comment.type().equals("Float")) {
boolean flag = value.matches(comment.regex());
if (!flag) {
System.out.print("Amount field wrong format.");
System.out.print("");
return "Amount field wrong format.";
}
}
}
return "";
}

/**
* Get the number of columns
* @return
*/
public int getColNum() {
if (!fileRows.toString().equals("[]")) {
if (fileRows.get(0).toString().contains(",")) {// csv为逗号分隔文件
return fileRows.get(0).toString().split(",").length;
} else if (fileRows.get(0).toString().trim().length() != 0) {
return 1;
} else {
return 0;
}
} else {
return 0;
}
}

/**
* 获取某个单元格
*
* @param row
* @param col
*             
* @return  
*/
public String getString(int row, int col) {
String temp = null;
int colnum = this.getColNum();
if (colnum > 1) {
temp = fileRows.get(row).toString().split(",")[col];
} else if (colnum == 1) {
temp = fileRows.get(row).toString();
} else {
temp = null;
}
return temp;
}

public static void main(String[] args) throws Exception {
//		账户名,付款时间,交易时间,金额
//		a375cbda,2015/5/30 0:00:00,2015-5-30 12:00:00,71.14
//		a375cbda,2015/5/30 0:00:00,2015-5-30 12:00:00,405.03
//		a375cbda,2015/5/30,2015-5-30 12:00:00,610.17
//		a375cbda,2015/5/30,2015-5-30 12:00:00,439.62
MyCsvUtil ss = new MyCsvUtil();
ss.checkFile("D:\\test\\订单发货1.csv");
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  date java CSV