Java讀取寫出CSV

教你三種方法,利用 OpenCSV 、javaCSV 與 BufferedReader/Writer 進行csv的讀取與寫出!

 

方法一:BufferedReader/Writer

讀取

  try {
   InputStreamReader isr = new InputStreamReader(new FileInputStream("D://file_input.csv"));//檔案讀取路徑
   BufferedReader reader = new BufferedReader(isr);
   BufferedWriter bw = new BufferedWriter(new FileWriter("D://file_output.csv"));//檔案輸出路徑
   String line = null;
   while((line=reader.readLine())!=null){
      String item[] = line.split(",");
      /** 讀取 **/
      String  data1= item[0].trim();
      String  data2= item[1].trim();
      String  data3= item[2].trim();
      System.out.print(data1+"\t"+ data2+"\t"+ data3+"\n"); 

      //可自行變化成存入陣列或arrayList方便之後存取
            }
   bw.close();
  } catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
   

也可以改成用陣列來接值!

String[] dataArray = {item[0].trim(),item[1].trim(),item[2].trim()};
System.out.print(dataArray[0]+"\t"+ dataArray[1]+"\t"+ dataArray[2]+"\n"); 

寫出

  try {
   InputStreamReader isr = new InputStreamReader(new FileInputStream("D://file_input.csv"));//檔案讀取路徑
   BufferedReader reader = new BufferedReader(isr);
   BufferedWriter bw = new BufferedWriter(new FileWriter("D://file_output.csv"));//檔案輸出路徑
   String line = null;
   while((line=reader.readLine())!=null){
                String item[] = line.split(",");

     /** 寫出 **/
    bw.newLine();//新起一行
   bw.write("data1,data2,data3");//寫到新檔案中

    //用陣列讀也可以,重點是中間記得加上"逗號",才可以順利分欄位
    //內容中如有逗號,記得換成別的,以免被csv誤會成分欄

   }
   bw.close();
  } catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }

用陣列讀也可以,點是中間記得加上"逗號",才可以順利分欄位!

/** 寫出 **/
String[] dataArray={data1,data2,data3};
bw.newLine();//新起一行
bw.write(data[0] +","+data[1] +","+ data[2]);//寫到新檔案中

內容中如有逗號,記得換成別的,以免被csv誤會成分欄

 

 

方法二:OpenCSV

請加入:opencsv.jar
http://www.java2s.com/Code/Jar/o/Downloadopencsv22jar.htm

讀取

1.使用Iterator方式讀

CSVReader reader = new CSVReader(new FileReader("File.csv")); 
String [] nextLine; 
while ((nextLine = reader.readNext()) != null) { 
    // nextLine[] is an array of values ​​from the line 
    System.out.println(nextLine[0] + nextLine[1] + "\n"); 
}

2. 使用List讀取

CSVReader reader = new CSVReader(new FileReader("File.csv")); 
List myEntries = reader.readAll();

寫出

CSVWriter writer = new CSVWriter(new FileWriter("File.csv"), '\t'); 
// feed in your array (or convert your data to an array) 
String[] entries1 = "data1,data2,data3". split(","); 
String[] entries2 = {"data1","data2","data3"]; 
writer.writeNext(entries1);
writer.writeNext(entries2);  
writer.close();

 

 

方法三:JavaCSV

請加入:javacsv.jar
http://www.java2s.com/Code/Jar/j/Downloadjavacsvjar.htm

讀取

try {
	CsvReader products = new CsvReader("File.csv");
	products.readHeaders();
	while (products.readRecord())
    {
		String data1= products.get("data id");
		String data2= products.get("data name");
		String data3= products.get("data price");	
		// perform program logic here
		System.out.println("id :" + data1);
	}
	products.close();
} catch (FileNotFoundException e) {
	e.printStackTrace();
} catch (IOException e) {
	e.printStackTrace();
}

寫出

String outputFile = "File_output.csv";
		// before we open the file check to see if it already exists
		boolean alreadyExists = new File(outputFile).exists();
		try {
			// use FileWriter constructor that specifies open for appending
			CsvWriter csvOutput = new CsvWriter(new FileWriter(outputFile, true), ',');
			
			// if the file didn't already exist then we need to write out the header line
			if (!alreadyExists){
				csvOutput.write("id");
				csvOutput.write("name");
				csvOutput.endRecord();
			}
			// else assume that the file already has the correct header line
			// write out a few records
			csvOutput.write("1");
			csvOutput.write("Bruce");
			csvOutput.endRecord();
			csvOutput.write("2");
			csvOutput.write("John");
			csvOutput.endRecord();
			csvOutput.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

 

 


同場加映:

Java讀取寫出檔案FileReader和FileWriter

 

 


參考來源:https://www.csvreader.com/java_csv_samples.php


 


人生美好~別浪費腦容量記程式碼 :- ) 

作者:CYL
出處:http://dotblogs.com.tw/cylcode
資料來源都會特別註明,有興趣都可查詢原出處,本站皆經過整理才分享,如有轉載請顯示出處及作者,感謝。