读取文件

import java.util.ArrayList;
import java.io.*;

public class ReadCSVFile {
 public static ArrayList readFile(String filename) {
  // BUG 000-000761
  FileReader fileReader = null;
  BufferedReader reader = null;
  ArrayList fileList = new ArrayList();

  try {
   File file = new File(filename);
   // BUG 000-000761
   //BufferedReader reader = new BufferedReader(new FileReader(file));
   fileReader = new FileReader(file);
   reader = new BufferedReader(fileReader);

   String strArray[] = null;
   String strStr = "";
   int strNum = 0;

   String csvArray[] = null;
   String csvStr = "";
   int csvNum = 0;

   ArrayList arr = null;
   int num;
   int cnt;

   String strCSV = null;

   while ((strCSV = reader.readLine()) != null) {
    arr = new ArrayList();
    if (strCSV.charAt(0) == '#') {
     continue;
    }

    if (strCSV.trim().length() == 0) {
     continue;
    }

    strArray = split(strCSV, ",");

    for (strNum = 0, cnt = strArray.length; strNum < cnt; strNum++) {
     strStr = strArray[strNum];
     if (strStr.indexOf("/"") != -1) {
      num = NumOfStr(strStr, '/"');
      if (num%2 == 1) {
       for (int i = strNum; i < cnt; i++) {
        csvStr = csvStr + strStr + ",";
        strNum = strNum + 1;
        strStr = strArray[strNum];
        num = NumOfStr(strStr, '/"');
        if (num%2 == 1) {
         csvStr = csvStr + strStr + ",";
         break;
        }
       }
      } else {
       csvStr = strStr;
      }
      csvStr = csvStr.substring(1, csvStr.length() - 3);
      csvStr = str2to1(csvStr);
     } else {
      csvStr = strStr;
      csvNum = csvNum + 1;
     }
     arr.add(Converter.rtrim(csvStr.trim()));
     csvStr = "";
    }

    fileList.add(arr);
   }
  } catch (Exception e) {
   fileList =  null;
  } finally {
  }

  // BUG 000-000761
  try {
   fileReader.close();
   reader.close();
  } catch (Exception e) {
   fileList = null;
  }

  return fileList;
 }

 private static String str2to1(String str) {
  String retStr = "";
  for (int i = 0, cnt = str.length(); i < cnt; i++) {
   retStr = retStr + str.charAt(i);
   if (str.charAt(i) == '"') {
    i++;
   }
  }
  return retStr;
 }

 private static int NumOfStr(String str, char findChar) {
  int num = 0;
  for (int i = 0, cnt = str.length(); i < cnt; i++) {
   if (str.charAt(i) == findChar) {
    num++;
   }
  }
  return num;
 }

 private static String[] split(String src, String regex) {
  StringBuffer strBuf = new StringBuffer(src);
  strBuf = strBuf.append(regex).append("x");
  String[] tmp = strBuf.toString().split(regex);
  String[] result = new String[tmp.length - 1];
  for (int i = 0; i < tmp.length - 1; i++) {
   result[i] = tmp[i];
  }
  return result;
 }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值