字符串 CSV解析 表格 逗号分隔值

CSV文件简介

逗号分隔值(Comma-Separated Values,CSV,有时也称为 字符分隔值,因为分隔字符也可以不是逗号),其文件 以纯文本形式存储表格数据(数字和文本)。纯文本意味着该文件是一个字符序列,不含必须像二进制数字那样被解读的数据。CSV文件由任意数目的记录组成,记录间以某种换行符分隔;每条记录由字段组成,字段间的分隔符是其它字符或字符串,最常见的是逗号或制表符。通常,所有记录都有完全相同的字段序列。通常都是纯文本文件。建议使用记事本来开启,再则先另存新档后用EXCEL开启,也是方法之一。

CSV文件格式的通用标准并不存在,但是在RFC 4180中有基础性的描述。使用的字符编码同样没有被指定,但是7-bitASCII是最基本的通用编码。

CSV是一种通用的、相对简单的文件格式,被用户、商业和科学广泛应用。最广泛的应用是 在程序之间转移表格数据,而这些程序本身是在不兼容的格式上进行操作的(往往是私有的和/或无规范的格式)。因为大量程序都支持某种CSV变体,至少是作为一种可选择的输入/输出格式。

“CSV”并不是一种单一的、定义明确的格式(尽管RFC 4180有一个被通常使用的定义)。因此在实践中,术语“CSV”泛指具有以下特征的任何文件:
  • 纯文本,使用某个字符集,比如ASCII、Unicode、EBCDIC或GB2312;
  • 由记录组成(典型的是每行一条记录);
  • 每条记录被分隔符分隔为字段(典型分隔符有逗号、分号或制表符;有时分隔符可以包括可选的空格);
  • 每条记录都有同样的字段序列。

在这些常规的约束条件下,存在着许多CSV变体,故CSV文件并不完全互通。然而,这些变异非常小,并且有许多应用程序允许用户预览文件(这是可行的,因为它是纯文本),然后指定分隔符、转义规则等。如果一个特定CSV文件的变异过大,超出了特定接收程序的支持范围,那么可行的做法往往是 人工检查并编辑文件,或通过简单的程序来修复问题。因此在实践中,CSV文件还是非常方便的。

解析工具类

数据格式:
微信号,bqt20094,这里是密码,邮箱#[email protected],QQ#909120849,
x
1
微信号,bqt20094,这里是密码,邮箱#909120849@qq.com,QQ#909120849,
工具类
//解析方式之所以定义成这样,是为了兼容我所使用的一款叫"密码本子"的APP
public class CsvUtils {
	private static final String COMMA = ",";
	private static final String SEPARATOR = "#";
	private static final String LINE_SEPARATOR = File.separator;
	private static final String ENCODING = "GBK";
	
	public static void obj2CsvFils(List<CsvBean> dataList, File file) {
		String content = obj2String(dataList);
		writeFile(content, file);
	}
	
	public static List<CsvBean> csvFils2Obj(String filePath) {
		String content = readFile(filePath);
		return string2Obj(content);
	}
	
	private static String obj2String(List<CsvBean> dataList) {
		StringBuilder sb = new StringBuilder();
		for (CsvBean cvsBean : dataList) {
			sb.append(cvsBean.name).append(COMMA).append(cvsBean.account).append(COMMA);
			if (isNotEmpty(cvsBean.password)) sb.append(cvsBean.password);//密码有可能为空
			sb.append(COMMA);
			if (cvsBean.other != null && !cvsBean.other.keySet().isEmpty()) {
				for (String key : cvsBean.other.keySet()) {
					String value = cvsBean.other.get(key);
					if (isNotEmpty(value)) sb.append(key).append(SEPARATOR).append(value).append(COMMA);
				}
			}
			sb.append(LINE_SEPARATOR);
		}
		return sb.toString();
	}
	
	private static void writeFile(String content, File file) {
		try {
			FileOutputStream writer = new FileOutputStream(file);
			writer.write(content.getBytes(ENCODING));
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private static List<CsvBean> string2Obj(String content) {
		if (content == null) return null;
		
		String[] array = content.split(LINE_SEPARATOR);
		List<CsvBean> list = new ArrayList<CsvBean>();
		for (String string : array) {
			int index = string.indexOf(COMMA);
			if (index >= 0) {
				CsvBean bean = new CsvBean();
				bean.name = string.substring(0, index);
				string = string.substring(index + 1);
				index = string.indexOf(COMMA);
				if (index >= 0) {
					bean.account = string.substring(0, index);
					string = string.substring(index + 1);
					index = string.indexOf(COMMA);
					if (index >= 0) {
						bean.password = string.substring(0, index);
						string = string.substring(index + 1);
						for (int i = 0; i <= string.length(); i++) {
							if (string.endsWith(",")) string = string.substring(0, string.length() - 1);
							else break;
						}
						if (string.length() > 0) {
							String[] otherStrings = string.split(COMMA);
							bean.other = new HashMap<>();
							for (String other : otherStrings) {
								String[] keyValue = other.split(SEPARATOR);
								if (keyValue.length >= 2) {
									bean.other.put(keyValue[0], keyValue[1]);
								}
							}
						}
					} else {
						bean.password = string;
					}
				} else {
					bean.account = string;
				}
				list.add(bean);
			}
		}
		return list;
	}
	
	private static String readFile(String filePath) {
		File file = new File(filePath);
		byte[] temp = new byte[(int) file.length()];
		try {
			FileInputStream in = new FileInputStream(file);
			in.read(temp);
			in.close();
			return new String(temp, ENCODING);
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}
	
	private static boolean isNotEmpty(String string) {
		return string != null && string.trim().length() > 0 && !string.equalsIgnoreCase("null");
	}
}
107
 
1
//解析方式之所以定义成这样,是为了兼容我所使用的一款叫"密码本子"的APP
2
public class CsvUtils {
3
    private static final String COMMA = ",";
4
    private static final String SEPARATOR = "#";
5
    private static final String LINE_SEPARATOR = File.separator;
6
    private static final String ENCODING = "GBK";
7
    
8
    public static void obj2CsvFils(List<CsvBean> dataList, File file) {
9
        String content = obj2String(dataList);
10
        writeFile(content, file);
11
    }
12
    
13
    public static List<CsvBean> csvFils2Obj(String filePath) {
14
        String content = readFile(filePath);
15
        return string2Obj(content);
16
    }
17
    
18
    private static String obj2String(List<CsvBean> dataList) {
19
        StringBuilder sb = new StringBuilder();
20
        for (CsvBean cvsBean : dataList) {
21
            sb.append(cvsBean.name).append(COMMA).append(cvsBean.account).append(COMMA);
22
            if (isNotEmpty(cvsBean.password)) sb.append(cvsBean.password);//密码有可能为空
23
            sb.append(COMMA);
24
            if (cvsBean.other != null && !cvsBean.other.keySet().isEmpty()) {
25
                for (String key : cvsBean.other.keySet()) {
26
                    String value = cvsBean.other.get(key);
27
                    if (isNotEmpty(value)) sb.append(key).append(SEPARATOR).append(value).append(COMMA);
28
                }
29
            }
30
            sb.append(LINE_SEPARATOR);
31
        }
32
        return sb.toString();
33
    }
34
    
35
    private static void writeFile(String content, File file) {
36
        try {
37
            FileOutputStream writer = new FileOutputStream(file);
38
            writer.write(content.getBytes(ENCODING));
39
            writer.close();
40
        } catch (IOException e) {
41
            e.printStackTrace();
42
        }
43
    }
44
    
45
    private static List<CsvBean> string2Obj(String content) {
46
        if (content == null) return null;
47
        
48
        String[] array = content.split(LINE_SEPARATOR);
49
        List<CsvBean> list = new ArrayList<CsvBean>();
50
        for (String string : array) {
51
            int index = string.indexOf(COMMA);
52
            if (index >= 0) {
53
                CsvBean bean = new CsvBean();
54
                bean.name = string.substring(0, index);
55
                string = string.substring(index + 1);
56
                index = string.indexOf(COMMA);
57
                if (index >= 0) {
58
                    bean.account = string.substring(0, index);
59
                    string = string.substring(index + 1);
60
                    index = string.indexOf(COMMA);
61
                    if (index >= 0) {
62
                        bean.password = string.substring(0, index);
63
                        string = string.substring(index + 1);
64
                        for (int i = 0; i <= string.length(); i++) {
65
                            if (string.endsWith(",")) string = string.substring(0, string.length() - 1);
66
                            else break;
67
                        }
68
                        if (string.length() > 0) {
69
                            String[] otherStrings = string.split(COMMA);
70
                            bean.other = new HashMap<>();
71
                            for (String other : otherStrings) {
72
                                String[] keyValue = other.split(SEPARATOR);
73
                                if (keyValue.length >= 2) {
74
                                    bean.other.put(keyValue[0], keyValue[1]);
75
                                }
76
                            }
77
                        }
78
                    } else {
79
                        bean.password = string;
80
                    }
81
                } else {
82
                    bean.account = string;
83
                }
84
                list.add(bean);
85
            }
86
        }
87
        return list;
88
    }
89
    
90
    private static String readFile(String filePath) {
91
        File file = new File(filePath);
92
        byte[] temp = new byte[(int) file.length()];
93
        try {
94
            FileInputStream in = new FileInputStream(file);
95
            in.read(temp);
96
            in.close();
97
            return new String(temp, ENCODING);
98
        } catch (IOException e) {
99
            e.printStackTrace();
100
            return null;
101
        }
102
    }
103
    
104
    private static boolean isNotEmpty(String string) {
105
        return string != null && string.trim().length() > 0 && !string.equalsIgnoreCase("null");
106
    }
107
}

数据模型

//数据结构之所以定义成这样,是为了兼容我所使用的一款叫"密码本子"的APP
public class CsvBean {
	public String name;//必选项
	public String account;//必选项
	public String password;//可选项
	public HashMap<String, String> other;//可选项

	@Override
	public String toString() {
		return "CvsBean [name=" + name + ", account=" + account + ", password=" + password + ", other=" + other + "]";
	}
}
12
 
1
//数据结构之所以定义成这样,是为了兼容我所使用的一款叫"密码本子"的APP
2
public class CsvBean {
3
    public String name;//必选项
4
    public String account;//必选项
5
    public String password;//可选项
6
    public HashMap<String, String> other;//可选项
7
8
    @Override
9
    public String toString() {
10
        return "CvsBean [name=" + name + ", account=" + account + ", password=" + password + ", other=" + other + "]";
11
    }
12
}
2018-9-8




猜你喜欢

转载自www.cnblogs.com/baiqiantao/p/9610165.html