【问题标题】:Read values with comma from csv in java用逗号从java中的csv读取值
【发布时间】:2014-03-05 06:05:59
【问题描述】:

我有以下代码可以从 android 中的 csv 文件中读取。当我的列值中有逗号时,它可以正常工作。

    File file = new File(IMPORT_ITEM_FILE.getPath());

    BufferedReader bufRdr = null;
    try {
        bufRdr = new BufferedReader(new FileReader(file));
    } catch (FileNotFoundException e) {

    }
    String line = null;

    try {
        while ((line = bufRdr.readLine()) != null) {

            String[] insertValues = line.split(",");


                string column1 = insertValues[1];

                string column2 = insertValues[2];
        }

        bufRdr.close();
    }

我的 csv 行是这样的:用户名 ,"some string, with commas","2740740, 2740608",,"some, string, with commas"

如何转义列值中的逗号以读取列。

【问题讨论】:

    标签: java android csv


    【解决方案1】:

    我建议你使用 http://opencsv.sourceforge.net/ 。如果您的 CSV 文件源文件格式正确,它将为您处理一切。

    示例用法:

    InputStream csvStream = getAssets().open(yourCSVFile);
            InputStreamReader csvStreamReader = new InputStreamReader(csvStream);
            CSVReader csvReader = new CSVReader(csvStreamReader);
            String[] line;
    
            while ((line = csvReader.readNext()) != null) {
                         String example = line[0]; // first item of your csv row
                      }
    

    【讨论】:

    • OpenCsv 解决了这个问题。我使用了他下面的代码CSVReader reader = new CSVReader(new FileReader("yourfile.csv")); String [] nextLine; while ((nextLine = reader.readNext()) != null) { // nextLine[] is an array of values from the line System.out.println(nextLine[0] + nextLine[1] + "etc..."); }
    【解决方案2】:

    我建议使用 RegEx 进行拆分。你可以使用类似:\"(.*?)\",?

    我没有在我使用的计算机上安装 Java,但类似这样的东西应该工作。但不能保证它会编译。

    String myString = "\"name of user\",\"official address, city\",\"2740740, 2740608\",,\"address, city, state\""
    
    Pattern myPattern = Pattern.compile("\"(.*?)\",?"); 
    Matcher myMatcher = myPattern.matcher(myString); // myPattern to match against string
    while (myMatcher.find())
    {
        System.out.println(myMatcher.group(1));
    }
    

    【讨论】:

    • 您的代码编译成功。但它只给了我双引号中包含的列值。跳过所有其他列
    • 啊,好吧,我以为你所有的值都在引号内。 RegEx 可能仍然有可能,但如果其他解决方案有效,那么这可能是一个更好的方法:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-15
    • 2018-09-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-23
    相关资源
    最近更新 更多