JAva解析csvファイル


最近のプロジェクトでは、大量のCSVファイルを処理する必要があり、これらのファイルをtxt形式に変換し、|で区切る必要があります.最も憂鬱なのは、これらのファイルのデータフォーマットの多くは規範的ではありません.
プロジェクトはJDK 1を使用するため.4,Stringの新しい特性は使うことができなくて、StringUtilクラスを書きました
今日また新しい問題に出会って、無言で、再びプログラムを修正しました
このコードは、フィールドに区切り記号、二重引用符などが表示されることを解決します.の
/**
	 *                     (          )                     TXT  
	 * 
	 * @throws Exception
	 */
	public static void specialChar(String filePath,int starRow) throws Exception {

		BufferedReader br = null;
		File f = new File(filePath);
		String fileName = f.getName();

		if (!fileName.substring(fileName.indexOf(".") + 1).equals("csv")) {
			throw new Exception(filePath + "    CSV  ");
		}
		File file = new File(StringUtil.replace(f.getPath(), "csv", "txt"));
		FileWriter filewriter = null;
		try {
			br = new BufferedReader(new InputStreamReader(
					new FileInputStream(f), "utf-8"));
			filewriter = new FileWriter(file, false);
			SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

			System.out.println(sd.format(new Date()));
			String tempString = null;
			int i = 0;
			while ((tempString = br.readLine()) != null) {
				if (i < starRow-1) {
					i++;
					continue;
				}
				if(tempString.trim().equals(""))
					break;
				if (StringUtil.contains(tempString, "\"")) {
					tempString = deepParser(tempString,filePath);
				} else
					tempString = StringUtil.replace(tempString, ",", "|");
//				System.out.println(tempString);
				filewriter.write(stringTrim(tempString, "\\|") + "\r
"); i++; } System.out.println(sd.format(new Date())); } catch (Throwable e) { log.warn(" :【" + filePath + "】 ", e); e.printStackTrace(); } finally { try { br.close(); filewriter.close(); } catch (IOException e) { e.printStackTrace(); } } } public static String deepParser(String str,String filePath) { System.out.println(str); String temp = str; str = str+","; StringBuffer sb = new StringBuffer(); try { int from = 0; int end = str.length(); int i = 0; while (StringUtil.contains((str = str.substring(from)), "\"")) { from = str.indexOf("\""); end = str.indexOf("\"", from + 1); sb.append(StringUtil.replace(str.substring(0, from), ",", "|")); sb.append(str.substring(from + 1, end)); from = end + 1; i++; } sb.append(StringUtil.replace(str, ",", "|")); } catch (Throwable e) { log.warn(" :【" + filePath + "】 , :"+temp, e); e.printStackTrace(); } String s = sb.toString(); s = s.substring(0, s.lastIndexOf("|")); return s; } // 2 , public static String stringTrim(String str, String regex) { str = str+" "; String[] strs = str.split(regex); StringBuffer sb = new StringBuffer(); for (int i = 0; i < strs.length; i++) { sb.append(strs[i].trim() + "|"); } return sb.toString().substring(0, sb.toString().lastIndexOf("|")); }