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

赫连靖琪
2023-12-01

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 List = new ArrayList();

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

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

{

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

 类似资料: