带有两个分隔符的 csv

csv with two delimiters

我正在尝试读取带有两个定界符的 csv,格式如下:

    Payment Date,Amount,Member No/branchno
    2018/01/25,58,294416/0

第一部分是日期,最后一列是我遇到问题的列。我需要在斜杠后将最后一列分成两列。

我的问题是我不知道如何在不影响第一列的情况下分隔最后一列,非常感谢任何帮助。

我已经可以通读 csv 并拆分逗号了。 这是读取 csv 的代码:

public ArrayList<String[]> ReadCSVFile(File DataFile)
    {    
        try(BufferedReader reader = new BufferedReader (new FileReader(DataFile));){ 

         //while loop to read through the data, while bufferedreader is not null-do .... 
                 while(reader.readLine()!= null)
                {
                    String read = reader.readLine();//bufferedreader string variable
                    String[] OneRow = read.split(","||"/");
                    rs2.add(OneRow);
                    System.out.println(Arrays.toString(OneRow));
        //            
                }
            //BufferedReader to Read through CSV Contents
                  reader.close();

    }//end try 
        catch(Exception ex){
        String errmsg = ex.getMessage();
        //System.out.println("File not Found: "+errmsg);
    }//end exception handling

你可以这样做;

while (reader.readLine() != null) {
    String read = reader.readLine();// bufferedreader string variable
    String[] rawRow = read.split(",");
    String lastEntry = rawRow[rawRow.length - 1]; // this contains Member No/branchno
    String[] properLastEntry = lastEntry.split("/"); // this contains Member No, branchno
    String[] oneRow = new String[rawRow.length + 1];
    System.arraycopy(rawRow, 0, oneRow, 0, rawRow.length - 1);
    System.arraycopy(properLastEntry, 0, oneRow, oneRow.length - 2, 2);
}

如果您不想在 properLastEntry 数组中对 2 的长度进行硬编码,您可以改为这样做

while (reader.readLine() != null) {
    String read = reader.readLine();// bufferedreader string variable
    String[] rawRow = read.split(",");
    String lastEntry = rawRow[rawRow.length - 1]; // this contains Member No/branchno
    String[] properLastEntry = lastEntry.split("/"); // this contains Member No, branchno as entries

    // create a memory which can contain rawRow and properLastEntry in a single
    // array
    String[] oneRow = new String[rawRow.length - 1 + properLastEntry.length];
    // copy the data for the finalRow
    System.arraycopy(rawRow, 0, oneRow, 0, rawRow.length - 1);
    System.arraycopy(properLastEntry, 0, oneRow, oneRow.length - properLastEntry.length,
            properLastEntry.length);
}

您想根据两个定界符拆分字符串,因此您可以按如下方式提及多个定界符

split(",|/")

请仔细阅读以下link。 Use string split() with multiple delimiters