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();
} } }
04-14 10:35