package util; 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; public class CSVReader { private File cvsFile; public CSVReader() { } public CSVReader(File cvsFile, File logFile) { this.cvsFile = cvsFile; } public File getCvsFile() { return cvsFile; } public void setcvsFile(File cvsFile) { this.cvsFile = cvsFile; } public void load(Loader loader) { try { // 读取CVS文件 BufferedReader reader = new BufferedReader(new FileReader(this.cvsFile)); // 逐行读取,并导入数据到数据库 String line = null; // 行号 int rownum = 1; while ((line = reader.readLine()) != null) { try { loader.load(parseLine(line)); } catch(Exception e) { } // 行号加一 rownum ++; } } catch (FileNotFoundException e) {} catch (IOException e) {} } private static List parseLine(String line) { // 解析字符串 List tokenList = new ArrayList(); StringBuffer token = new StringBuffer(); // 是否在引号内 boolean inQuotation = false; for (int i = 0; i < line.length(); i++) { char c = line.charAt(i); if (c == ',' && !inQuotation) { tokenList.add(token.toString()); token.setLength(0); } else if (c == '"') { if (inQuotation) { char d = line.charAt(i+1); if (d == '"') { token.append(c); i ++; } else { inQuotation = !inQuotation; } } else { inQuotation = !inQuotation; } } else { token.append(c); } } tokenList.add(token.toString()); // 返回解析结果 return tokenList; } public static void main(String[] args) throws Exception { CSVReader.readCSV("D:/TestFile1.csv"); File cvsFile = new File("D:/TestFile1.csv"); File logFile = new File("D:/Load.log"); CSVReader loader = new CSVReader(cvsFile, logFile); loader.load(new Loader(){ public void load(List recFieldList) throws Exception{ for (int i = 0; i < recFieldList.size(); i++) { System.out.println("F[" + i + "]=" + recFieldList.get(i).toString().replaceAll("'", "")); } } }); } public static List readCSV(String filepath) throws IOException { //filepath ="D:/TestFile1.csv" File file = new File(filepath);//到目录下取文件 BufferedReader br = null; List list = new ArrayList(); try { br = new BufferedReader(new InputStreamReader( new FileInputStream(file)));//获得文件流 String line = null; while ((line = br.readLine()) != null) {//读取一行 list.add(line.replaceAll("'","").split(",")); } } finally { if (br != null) { br.close(); } } return list; } }
java解析.csv文件,java解析CSV文件
最新推荐文章于 2024-08-29 17:06:19 发布