del格式类似csv,我这里的测试文件test.del是从DB2数据库中导出来的一组数据。
apache commons csv的maven坐标为:
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-csv -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-csv</artifactId>
<version>1.5</version>
</dependency>
测试程序:
package test;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
public class DelFileParser {
public static List< List<String> > parseFile(File file) {
List resList = new ArrayList< List<String> >();
try {
InputStream is = new FileInputStream(file);
InputStreamReader reader = new InputStreamReader(is, "GB2312");
CSVParser parser = new CSVParser(reader, CSVFormat.DEFAULT);
for (CSVRecord record : parser) {
List<String> tmpList = new ArrayList<String>();
for (String s : record) {
if (s != null)
s = s.trim();
tmpList.add(s);
}
resList.add(tmpList);
}
is.close();
reader.close();
return resList;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public static void main(String[] args) {
List< List<String> > resList = parseFile(new File("D:\\test.del"));
// test
for (List<String> tmpList : resList) {
for (String s : tmpList) {
System.out.print(s + ",");
}
System.out.println();
}
}
}
采用default格式不会将第一行当成Header。
更多资料参见:http://commons.apache.org/proper/commons-csv/user-guide.html
原文地址:https://www.cnblogs.com/zifeiy/p/9175837.html
时间: 2024-11-06 07:33:48