I need to parse a space- delimited text file. I want to read the file and do operations for each cell. Here is how I am parsing the file:

String line;
BufferedReader reader = new BufferedReader(new FileReader(file));
Map<String,String> mapFile = new HashMap<String, String>(19); 
while((line = reader.readLine()) != null) {
    mapFile.put("valueCol1", line.substring(0,19));
    mapFile.put("valueCol2", line.substring(19,45));
    mapFile.put("valueCol3", line.substring(45,50));
    mapFile.put("valueCol4", line.substring(50,54));

Is this right, or should I use other types of collections?

  • \$\begingroup\$ Wait. Aren't you (always) overwrite the previous line with the current one? \$\endgroup\$
    – coderodde
    Apr 22, 2016 at 9:00
  • \$\begingroup\$ Also, could you post the entire method containing your current code snippet? This will bring the context into awareness, and, thus, allow better answers. \$\endgroup\$
    – coderodde
    Apr 22, 2016 at 9:10
  • \$\begingroup\$ Welcome to Code Review! Does your code work as you would like it to? \$\endgroup\$
    – SirPython
    Apr 22, 2016 at 14:07

1 Answer 1


It really depends on what you're using the map for. As already raised, you are overwriting the map for each line you read.

If you want to do something with the data later then I'd recommend creating a custom object with the fields for each column. Then you could store it in a list or a map with one of the values as a key (the value should be unique to prevent clashes) for future use.

If you're operating on it within the line read loop then you don't even need a data structure, just operate on the data right there and then.

Really until we know what you want to do with the data it is hard to say if you're using the correct data structure.

As a final note you state it is space delimited, I'd probably use String.split(" ") to create an array of your column data instead of using absolute references in your substring call, this would allow for cases where the data is larger than your substring range but still delimited by a space, unless you're absolutely sure the data is in a fixed format and is clean.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.