'custom file parser written in java needs improvement
I've written parser in java for a structured binary file. Each field of the file starts the same way: it starts with a specific byte (introducer), the field length, field type and the field data. E.g. (in hex): 4200110A010203... Would be: Introducer: 42 field length: 0011 -> 17 bytes field type: 0A data: 010203...
But the way I've written the parser feels a bit cumbersome, especially the part about reading/interpreting the field data. And I wanted to ask you if there is a better way or even a standard approach to this. I mean this part:
package example;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Converter {
private static final Map<String, Convert<Node, ?>> map = new HashMap<>();
static {
map.put("0A", Converter::getTypeA);
map.put("0B", Converter::getTypeB);
map.put("0C", Converter::getTypeC);
}
public static Node convert(Node node) {
return (Node) map.get(node.getIdentifier()).convert(node);
}
private static Node getTypeA(Node node) {
int id = Util.toInteger(new byte[]{node.getData()[4], node.getData()[5]});
String value = Util.toString(node.getData(), 6);
return new TypeA(node.getPosition(), node.getLength(), node.getIdentifier(), node.getData(), id, value);
}
private static Node getTypeB(Node node) {
int id = Util.toInteger(new byte[]{node.getData()[4], node.getData()[5]});
List<String> values = new ArrayList<>();
int offset = 6;
while(offset < node.getData().length) {
int length = node.getData()[offset] & 0xFF;
values.add(Util.toString(node.getData(), offset + 1, length));
offset += 1 + length;
}
return new TypeB(node.getPosition(), node.getLength(), node.getIdentifier(), node.getData(), id, values);
}
private static Node getTypeC(Node node) {
String value = Util.toString(node.getData(), 4, 8);
byte[] data = new byte[node.getData().length - value.length()];
return new TypeC(node.getPosition(), node.getLength(), node.getIdentifier(), node.getData(), value, data);
}
}
Here is a complete example (can create files with random amount of data and then parse it back):
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
