简体   繁体   中英

Parsing a CSV file with custom String separator

I tried to parse a CSV file with two APIs - JSefa and OpenCSV - but the problem is that the separator in the CSV file is a double tab "\\t\\t" and the APIs only accept a character, not a string, for the separator.

Is there any other API that could solve the problem, or there sa way to determine a new String separator in Jsefa or OpenCSV?

As a last resort I could, before parsing, try to replace the double tab by a semicolon but I was hoping to do it a cleaner way.

There's 101 examples online. I Googled "java parse csv" and this was the #1 result:

http://www.mkyong.com/java/how-to-read-and-parse-csv-file-in-java/

That uses a String as a separator, however this is code rather than an API.

Given that parsing a CSV file is a pretty simple process, I don't think it's a good example of a situation requiring a library and - especially with a slightly unique requirement like you have with the strange \\t\\t separator - it is probably better to just code it anyway.

try this:

ArrayList<String> itemsOne=new ArrayList<String>();
ArrayList<String> itemsTwo=new ArrayList<String>();

InputStream is = getResources().openRawResource(R.raw.csvfile);
try {
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    String line;

    while ((line = reader.readLine()) != null ) {
        String [] rowData = line.split("\t\t");
        itemsOne.add(rowData[0]);
        itemsTwo.add(rowData[1]);
    }
} catch (Exception e) {}

yes its correct that opencsv does not support String as deleimiter.

one simple solution is to use '\\t' as delimiter and ignore empty fields.

for example :

String s = "1\t\t2\t\t3\t\t4";

to

String[7] fields;
fields[0] = "1";
fields[1] = "";
fields[2] = "2";
fields[3] = "";
...

您建议的解决方案(用分隔符替换分隔符字符串似乎是最好的方法,这很容易并且可以解决您的问题。CSV是一种非常简单的格式,如果您通过添加复杂的分隔符对其进行修改,则它不是“逗号分隔”值”格式。请保持简单!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM