Code example for StringTokenizer

Methods: countTokens, nextToken

0
public class UserCodec implements Codec<User> { 
    private static final String SEPARATOR = ";";
 
    @Override 
    public User fromCode(final String codeLine) throws Exception {
        final StringTokenizer tokenizer = new StringTokenizer(codeLine, SEPARATOR, false);
        if (tokenizer.countTokens() < 3) {
            throw new Exception("La ligne doit etre avoir le format suivant : id;prenom;nom");
        } 
        return new User(valueOf(tokenizer.nextToken()), tokenizer.nextToken(), tokenizer.nextToken());
    } 
 
    @Override 
    public String toCode(final User user) {
        final StringBuilder buffer = new StringBuilder();
        buffer.append(user.getId()).append(SEPARATOR);
        buffer.append(user.getFirstName()).append(SEPARATOR);
        buffer.append(user.getName());
        return buffer.toString();
    } 
}