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

java使用CsvReader和CsvWriter对csv文件内容进行读取和写入操作

2017-12-13 12:55 1246 查看
package IO;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;

import com.csvreader.CsvReader;
import com.csvreader.CsvWriter;

public class IO {
public String inPath="D:\\中国农业银行全国网点大全.csv";
public String outPath="D:\\网点大全.csv";
public ArrayList<String []> List = new ArrayList<String[]>();
private void CheckandCreateFile(){

File file=new File(outPath);
try{
if(!file.exists()){
file.createNewFile();
System.out.println("文件不存在,新建成功!");
}
else{
System.out.println("文件存在!");
}
}catch( Exception e){
e.printStackTrace();
}
}

public void ReadCSV() throws IOException {

CsvReader reader = new CsvReader(inPath,',', Charset.forName("gb2312"));
reader.readHeaders();
while(reader.readRecord()) {
List.add(reader.getValues());
}
reader.close();
for (int row = 0;row < List.size(); row++) {
int Length=List.get(row).length;
if(Length > 0){
for(int i=0;i<Length;i++){
System.out.print(List.get(row)[i]+",");
}//for

}//if
System.out.println("");
}//for

}//class
public void WriteCSV()	throws IOException{
IO IO=new IO();
IO.CheckandCreateFile();
CsvWriter wr = new CsvWriter(outPath,',', Charset.forName("gb2312"));
String[] header = { "Name","Province","City","Address","Tel","Website","Server_content","Jigou_cengji","Type","Parent_level1","Parent_level2","Branch_level" };
wr.writeRecord(header);
for(int i=0;i<List.size();i++)
{
String[] Data= List.get(i);
wr.writeRecord(Data);
}
wr.close();
}
public static void main( String args[]) throws IOException{
IO IO=new IO();
IO.ReadCSV();
IO.WriteCSV();
}
}


javacsv2.0.jar下载

链接:https://pan.baidu.com/s/1jId68zs 密码:7r7j
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: