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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Yuan52007298/article/details/78790660

 

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

阅读更多
换一批

没有更多推荐了,返回首页