- import java.io.BufferedReader;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileNotFoundException;
- import java.io.FileReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.StringTokenizer;
- public class CsvResolve {
- public List<String[]> readCsv(String csvfilePath,String encodingCharSet)
- {
- List<String[]> resultList=new ArrayList<String[]>();
- try {
- FileInputStream csvfileInputStream = new FileInputStream(csvfilePath);
- InputStreamReader csvfileInputStreamReader = new InputStreamReader(csvfileInputStream , encodingCharSet);
- BufferedReader csvfileBufferedReader = new BufferedReader(csvfileInputStreamReader);
- String line = csvfileBufferedReader.readLine();
- String[] firstLineElements=line.split("\t");
- //輸出第一行的內容
- for(int i=;i<firstLineElements.length;i++)
- {
- System.out.println(i+"\t"+firstLineElements[i]);
- }
- System.out.println();
- while ((line = csvfileBufferedReader.readLine()) != null) {
- String[] otherLineElements=line.split("\t");
- //如果結尾處有一個或多個tab鍵,說明,最後缺失的有元素
- //先把字串陣列轉化為list,讓後新增元素,然後再把新增完元素的list
- //轉化為字串陣列
- if(otherLineElements.length<firstLineElements.length)
- {
- String[] toaddOtherLineElements;
- List<String> tempList=new ArrayList<String>();
- int i=;
- for(;i<otherLineElements.length;i++)
- {
- if(otherLineElements[i].equals(""))
- {
- tempList.add(null);
- }else{
- tempList.add(otherLineElements[i]);
- }
- }
- for(;i<firstLineElements.length;i++)
- {
- tempList.add(null);
- }
- toaddOtherLineElements=tempList.toArray(new String[]);;
- resultList.add(toaddOtherLineElements);
- }
- //如果長度相同說明最後的元素存在
- else{
- String[] toaddOtherLineElements;
- List<String> tempList=new ArrayList<String>();
- int i=;
- for(;i<otherLineElements.length;i++)
- {
- if(otherLineElements[i].equals(""))
- {
- tempList.add(null);
- }else{
- tempList.add(otherLineElements[i]);
- }
- }
- toaddOtherLineElements=tempList.toArray(new String[]);;
- resultList.add(toaddOtherLineElements);
- }
- }
- csvfileBufferedReader.close();
- } catch (FileNotFoundException e) {
- // 捕獲File物件生成時的異常
- e.printStackTrace();
- } catch (IOException e) {
- // 捕獲BufferedReader物件關閉時的異常
- e.printStackTrace();
- }
- return resultList;
- }
- public static void main(String[] args) {
- CsvResolve csvResolve=new CsvResolve();
- List<String[]> csvContent=csvResolve.readCsv("d:/csv/1.csv","utf-8");
- for(int i=;i<csvContent.size();i++)
- {
- String[] temp=csvContent.get(i);
- for(int j=;j<temp.length;j++)
- {
- System.out.println(j+"\t"+temp[j]);
- }
- System.out.println();
- }
- }
- }