java中读取和存储数据到CSV格式的文件中。
什么是CSV
CSV是一种通用的、相对简单的文件格式,其文件以纯文本形式存储表格数据(数字和文本)。
CSV格式的特点
由于CSV是一种纯文本的文件,因此其具有以下几个特点
支持追加模式写入,节省内存。
CSV的文件行数没有限制。
CSV是纯文本文件,可以使用任何文本编辑器进行编辑。
public class Text2CSV {
//导出到csv文件
public static void Array2CSV(ArrayList<ArrayList<String>> data, String path,int num)
{
int getPhoneNum = 19;
num = getPhoneNum;
try {
BufferedWriter out =new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path),"UTF-8"));
for (int i = 0; i < data.size(); i++)
{
ArrayList<String> onerow=data.get(i);
//ArrayList<String> onerow=data.get(i);
for (int j = 0; j < onerow.size(); j++)
{
out.write(DelQuota(onerow.get(j)));
out.write(",");
}
out.newLine();
}
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static String DelQuota(String str)
{
String result = str;
String[] strQuota = { "~", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "`", ";", "'", ",", ".", "/", ":", "/,", "<", ">", "?" };
for (int i = 0; i < strQuota.length; i++)
{
if (result.indexOf(strQuota[i]) > -1)
result = result.replace(strQuota[i], "");
}
return result;
}
//从csv文件中读取数据
public static ArrayList<ArrayList<String>> CSV2Array(String path)
{
try {
BufferedReader in =new BufferedReader(new InputStreamReader(new FileInputStream(path),"UTF-8"));
ArrayList<ArrayList<String>> alldata=new ArrayList<ArrayList<String>>();
String line;
String[] onerow;
while ((line=in.readLine())!=null) {
onerow = line.split(","); //默认分割符为逗号,可以不使用逗号
List<String> onerowlist = Arrays.asList(onerow);
ArrayList<String> onerowaArrayList = new ArrayList<String>(onerowlist);
alldata.add(onerowaArrayList);
}
in.close();
return alldata;
} catch (Exception e) {
return null;
}
}
}
可以通过下面的代码进行测试,可以发现能正常的进行读取和输出csv格式的文件。
public static void main(String[] args) {
String str[] = new String[10000];
for (int i = 0; i < str.length; i++) {
str[i] = i +"";
}
//自定义数组
ArrayList<ArrayList<String>> alldata = new ArrayList<ArrayList<String>>();
alldata.add(new ArrayList<String>(Arrays.asList(str))); //添加一行
alldata.add(new ArrayList<String>(Arrays.asList(str))); //添加一行
alldata.add(new ArrayList<String>(Arrays.asList(str))); //添加一行
//保存成csv文件
Array2CSV(alldata, "test.csv",19);
//读取csv文件
ArrayList<ArrayList<String>> alldata1 = CSV2Array("test.csv");
/* //遍历数组
for (ArrayList<String> arrayList : alldata1) {
for (String string : arrayList) {
System.out.println(string);
}
}*/
}
}