带有两个分隔符的csv

时间:2018-03-20 07:05:18

标签: java csv bufferedreader delimiter-separated-values

我正在尝试读取带有两个分隔符的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

2 个答案:

答案 0 :(得分:0)

你可以做这样的事情;

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

如果您不想在2数组中对properLastEntry的长度进行硬编码,则可以执行以下操作

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

答案 1 :(得分:0)

您希望基于两个分隔符拆分字符串,以便您可以提及多个分隔符,如下所示

split(",|/")

请浏览以下链接。 Use string split() with multiple delimiters

相关问题