4

我正在阅读一个 CSV 文件并有一些值,例如

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

在将文件读入StringBuilder并转换后,toString()我将文件内容拆分为:string.split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)");.

在迭代字符串时,我得到这些值: -

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();
    }

}
4

2 回答 2

10

使用String#replace(CharSequence, CharSequence).

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

http://ideone.com/xPQqL

于 2012-08-09T19:32:12.967 回答
2
String[] tokens = read.split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)");
for(int i = 0;i<tokens.length;i++)
    tokens[i]=StringEscapeUtils.unescapeCsv(tokens[i]);
于 2013-08-16T12:58:14.527 回答