2012-08-09 305 views
3

我读一个CSV文件,并有一定的价值像

field 1 field 2   field 3 
1  test case1   expecting one, and \"two\", and three 

读文件到StringBuilder和转换toString()后,我通过分割文件内容。

在遍历字符串我得到这些值: -

1 
test case1 
expecting one, and ""two"", and three 

我如何我喜欢单,双替换两个双引号这个“二”

这里是我的代码: -

import java.io.BufferedReader; 
import java.io.FileReader; 
import java.io.IOException; 


public class csvStringParser { 

    /** 
    * @param args 
    * @throws IOException 
    */ 
    public static void main(String[] args) throws IOException { 
     // TODO Auto-generated method stub 


      String path = "E:/spc.csv"; 

      String read = readFile(path); 
      System.out.println("content of the file before \" = \n" +read); 



//  System.out.println("content of the file after= \n" +read); 

     String[] tokens = read.split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)"); 
      for(int i = 0;i<tokens.length;i++) { 
       String abc = tokens[i].replace("\"\"", "\""); 

      // if(abc.length()>2){ 
       if(abc.startsWith("\"") && abc.endsWith("\"")){ 
       abc = abc.substring(1, abc.length()-1); 
       } 
      // } 

       System.out.println("> "+abc); 
      } 

    } 

    public static String readFile(String file) throws IOException { 
     BufferedReader reader = new BufferedReader(new FileReader (file)); 
     String   line = null; 
     StringBuilder stringBuilder = new StringBuilder(); 
     String   ls = System.getProperty("line.separator"); 

     while((line = reader.readLine()) != null) { 
      stringBuilder.append(line); 
      stringBuilder.append(ls); 
     } 

     return stringBuilder.toString(); 
    } 

} 

回答

8

使用String#replace(CharSequence, CharSequence)

String input = "this string \"\"has\"\" double quotes"; 
String output = input.replace("\"\"", "\""); 

http://ideone.com/xPQqL

+0

不工作对我来说,如果我写串读= READFILE(路径); read.replace(“\”\“”,“\”“); – user1371033 2012-08-09 19:37:54

+0

您是否看到我的代码?有没有什么我做错了? – user1371033 2012-08-09 19:47:58

+0

我现在看到它了,不,我没有看到明显的东西。你能整理一个ideone的例子吗? – 2012-08-09 19:50:06

1
String[] tokens = read.split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)"); 
for(int i = 0;i<tokens.length;i++) 
    tokens[i]=StringEscapeUtils.unescapeCsv(tokens[i]);