1

I have a requirement to read a pipe delimited file and have it populated in a String array and pass it as a list back and do further processing below.

Sample data : X|ABCD|001111006|1111006|ABC|test006| | | | | |C|||||||||||||
    Note : Sample data can have both NULL and space between pipe 

This is working fine if data is available in all the pipe delimits , atleast a space, but for the null values in between the pipe

There are 26 attributes and whenever there are NULL the array index is not incremented from the cardinal where NULL was available . Say when there is a NULL at 12 th pipe the array is not populated till 25 it stops at 12 and this is craeting issue in my further processing

and the file can have both NULL and space. Can you help me solve this issue

public List<String[]> readFile(String FileName) {

final List<String[]> userList = new ArrayList<String[]>(); 
BufferedReader bufferedreader = null;
try {

    int i=0;
    bufferedreader = new BufferedReader(new FileReader(FileName));
    String line = null;

     while ((line = bufferedreader.readLine()) != null) {      
          final String[] values = line.split("\\|");
          userList.add(values);   
      } 
}
catch (FileNotFoundException ex) {
    CTLoggerUtil.logError(ex.getMessage());
}
catch (IOException ex) {
    CTLoggerUtil.logError(ex.getMessage());
}
finally {
  try {
    if (bufferedreader != null)
    {
        bufferedreader.close();}
  }
  catch (IOException ex) {
      CTLoggerUtil.logError(ex.getMessage());


  }
}

 return userList;
  }
user549432
  • 137
  • 2
  • 8
  • 20
  • 1
    The documentation of String.split() says that consecutive delimitiers are not taken as one. Could you check what values.length is after the split? – SJuan76 Jul 13 '11 at 23:45

1 Answers1

4

By default, String.split() discards empty trailing strings. If you set a negative limit, you will get all empty results back as well:

final String[] values = line.split("\\|", -1);
Jeen Broekstra
  • 21,642
  • 4
  • 51
  • 73
  • Thanks this worked . This is exactly what I wanted . Also there are spaces in place of nulls. Is there any way I can retain NULLS in input as NULLS and space in input as space or is it not possible ? Thanks a lot for your help – user549432 Jul 14 '11 at 02:41
  • With the above method your array will contain " " for the spaces, and "" (empty string) for the null-values. So you can distinguish between the two. If your question is if the split can actually put null in the array for each null value (instead of an empty string), I think the answer is no. – Jeen Broekstra Jul 14 '11 at 04:11