Alternative to create a new method a String object?

I'm facing with a issue: I have a csv file to prepare and extract values. Here is the code (and works fine):

public class Extract {

final int[] ID = new int[]{0, 10};
final int[] NAME = new int[]{15, 45};

public static void main(String args[]) {

  FileInputStream fis = new FileInputStream("C:\\cnab.txt");        
  String line;

  while ((line = fis.readLine()) != null) {
      System.out.println(getValue(line, ID));
      System.out.println(getValue(line, NAME)); 
  }
}

private String getValue(String line, int[] slice) {
    return line.substring(slice[0], slice[1]);
}

}

Until then ok , but I would like something more readable , elegant, such as:

System.out.println(line.getValue(NAME));

But we all know that String is final (and so should be). Anyone have any suggestions ?

Jon Skeet
people
quotationmark

One option would be to have an enum where you've currently got int arrays:

public enum Field {
    ID(0, 10),
    NAME(15, 45);

    private final int start;
    private final int end;

    private Field(int start, int end) {
        this.start = start;
        this.end = end;
    }

    public string extractFrom(String line) {
        return line.substring(start, end);
    }
}

Then:

System.out.println(Fields.NAME.extractFrom(line));
System.out.println(Fields.ID.extractFrom(line));

This means you can pass around fields (e.g. to have a set of required fields for validation) without them just being int[], which could mean anything - and you can add any other custom methods and information you want. (For example, for validation you could have a Pattern field...)

people

See more on this question at Stackoverflow