java读取csv
import java.io.File;
import java.io.FileNotFoundException; import java.io.IOException;
import java.nio.charset.Charset; import java.util.ArrayList;
import java.util.List;
Mc1081
import org.apache.log4j.Logger;
import com.csvreader.CsvReader;
import com.csvreader.CsvWriter;
/**
* CSV?âÊÔÀà
*
*/
public class CSVTest {
protected static Logger logger = Logger.getLogger(CSVTest.class);
/**
* ?ÁÈ?CSVÎÄ?þ
* @param file
* @return
*/
public static List readCsv(String file) {
List list = new ArrayList();
CsvReader reader = null;
try {
// ?õÊ???CsvReader??Ö???ÁÐ?Ö?ô?ûºÍ×Ö?û?àÂë
reader = new CsvReader(file, ',', Charset.forName("GBK"));
while (reader.readRecord()) {
// ?ÁÈ?Ã?ÐÐÊý?ÝÒÔÊý×éÐÎÊ??µ?Ø
String[] str = reader.getValues();
if (str != null && str.length > 0) {
if (str[0] != null && !"".equals(str[0].trim())) {
System.out.println(str.length);
System.out.println(str[1]);
list.add(str);
}
}
}
} catch (FileNotFoundException e) {
logger.error(e.getMessage(), e);
} catch (IOException e) {
logger.error(e.getMessage(), e);
} finally {
if (reader != null) {
reader.close();
}
}
return list;
}
/**
* Ð?ÈëCSVÎÄ?þ
*/
public static void writeCsv(List content, String path)
{
CsvWriter writer = null;
try {
writer = new CsvWriter(path, ',', Charset.forName("GBK"));
if(content != null && content.size() != 0) {
for(String[] strArray : content) {
writer.writeRecord(strArray);
}
} else {
// ×öÒì????Àí
}
} catch (IOException e) {
logger.error(e.getMessage(), e);
} finally {
if(writer != null) {
writer.close();
}
}
}
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
String readPath = "F:" + File.separator + "test" + File.separator
+ "muti-test.csv";
String writePath = "F:" + File.separator + "test" +
File.separator + "muti-test-output.csv";
List result = readCsv(readPath);
for(String[] strArray : result) {
for(String s : strArray) {
System.out.print(s + ",");
}
System.out.println();
}
writeCsv(result, writePath);
Thread.sleep(999999);
}
}