/** * Creates a new instance initialized from {@link FixedWidth} annotations in the fields and methods of a given class. Note that * all fields should additionally have the {@link Parsed} annotation to configure header names and/or their positions. * * Only getter methods will be considered as fields. * * @param beanClass the class whose {@link FixedWidth} annotations will be processed to configure this field list. * * @return a new {@link FixedWidthFields} instance built with the {@link FixedWidth} annotations found in the given class' attributes and methods (excluding setters) */ public static FixedWidthFields forWriting(Class beanClass) { return new FixedWidthFields(beanClass, MethodFilter.ONLY_GETTERS); }
/** * Creates a new instance initialized with the lengths of all fields in a fixed-width record. * * @param fieldLengths The number lengths of all fields in a fixed-width record. All lengths must be greater than 0. */ public FixedWidthFields(int... fieldLengths) { for (int i = 0; i < fieldLengths.length; i++) { addField(fieldLengths[i]); } }
/** * Returns the alignment of a given field. An {@code IllegalArgumentException} will be thrown if no names have been defined. * * @param fieldName the name of the field whose alignment will be returned * * @return the alignment of the given field */ public FieldAlignment getAlignment(String fieldName) { int index = indexOf(fieldName); if (index == -1) { throw new IllegalArgumentException("Field '" + fieldName + "' does not exist. Available field names are: " + this.fieldNames); } return getAlignment(index); }
Lookup(String value, FixedWidthFields config, FixedWidthFormat format) { this.value = value.toCharArray(); this.lengths = config.getAllLengths(); this.alignments = config.getFieldAlignments(); this.fieldNames = config.getFieldNames(); this.paddings = config.getFieldPaddings(format); this.wildcard = format.getLookupWildcard(); this.ignore = config.getFieldsToIgnore(); this.keepPaddingFlags = config.getKeepPaddingFlags(); }
FixedWidthFields accountFields = new FixedWidthFields(); accountFields.addField("ID", 10); //account ID has length of 10 accountFields.addField("Bank", 8); //bank name has length of 8 accountFields.addField("AccountNumber", 15); //etc accountFields.addField("Swift", 12); //Format for clients' records FixedWidthFields clientFields = new FixedWidthFields(); clientFields.addField("Lookahead", 5); //clients have their lookahead in a separate column clientFields.addField("ClientID", 15, FieldAlignment.RIGHT, '0'); //let's pad client ID's with leading zeroes. clientFields.addField("Name", 20); FixedWidthWriterSettings settings = new FixedWidthWriterSettings(); settings.getFormat().setLineSeparator("\n"); settings.getFormat().setPadding('_'); //If a record starts with C#, it's a client record, so we associate "C#" with the client format. settings.addFormatForLookahead("C#", clientFields); //Rows starting with #A should be written using the account format settings.addFormatForLookahead("A#", accountFields); StringWriter out = new StringWriter(); //Let's write FixedWidthWriter writer = new FixedWidthWriter(out, settings); writer.writeRow(new Object[]{"C#",23234, "Miss Foo"}); writer.writeRow(new Object[]{"A#23234", "HSBC", "123433-000", "HSBCAUS"}); writer.writeRow(new Object[]{"A#234", "HSBC", "222343-130", "HSBCCAD"}); writer.writeRow(new Object[]{"C#",322, "Mr Bar"}); writer.writeRow(new Object[]{"A#1234", "CITI", "213343-130", "CITICAD"}); writer.close(); System.out.println(out.toString());
addField(fieldName, length, alignment, padding); } else if (from != -1 && to != -1) { addField(fieldName, from, to, alignment, padding); } else { throw new IllegalArgumentException("Can't initialize fixed-width field from " + field.describe() + "'. " + setKeepPaddingFlag(keepPadding, fieldLengths.size() - 1);
@Override protected void configureFromAnnotations(Class<?> beanClass) { if (fieldLengths != null) { return; } try { fieldLengths = FixedWidthFields.forWriting(beanClass); Headers headerAnnotation = AnnotationHelper.findHeadersAnnotation(beanClass); setHeaderWritingEnabled(headerAnnotation != null && headerAnnotation.write()); } catch (Exception ex) { //ignore. } super.configureFromAnnotations(beanClass); FixedWidthFields.setHeadersIfPossible(fieldLengths, this); }
@Override protected void configureFromAnnotations(Class<?> beanClass) { if (fieldLengths == null) { try { fieldLengths = FixedWidthFields.forParsing(beanClass); Headers headerAnnotation = AnnotationHelper.findHeadersAnnotation(beanClass); if (headerExtractionEnabled == null && headerAnnotation != null) { setHeaderExtractionEnabled(headerAnnotation.extract()); } } catch (IllegalArgumentException e) { throw e; } catch (Exception ex) { //ignore. } } if (headerExtractionEnabled == null) { setHeaderExtractionEnabled(false); } super.configureFromAnnotations(beanClass); if (!isHeaderExtractionEnabled()) { FixedWidthFields.setHeadersIfPossible(fieldLengths, this); } }
/** * Clones this configuration object to reuse most user-provided settings. This includes the fixed-width field configuration, * but doesn't include other input-specific settings. This method is meant to be used internally only. * * @return a copy of all configurations applied to the current instance. * * @deprecated doesn't really make sense for fixed-width. Use alternative method {@link #clone(FixedWidthFields)}. */ @Deprecated protected final FixedWidthParserSettings clone(boolean clearInputSpecificSettings) { return clone(clearInputSpecificSettings, fieldLengths == null ? null : fieldLengths.clone()); }
int[] getAllLengths() { if (fieldLengths == null) { return null; } return fieldLengths.getAllLengths(); }
/** * Function to create a univocity Parser */ private void createUnivocityParser() { List<FixedWidthSchema.Field> fields = schema.getFields(); FixedWidthFields fieldWidthFields = new FixedWidthFields(); for (int i = 0; i < fields.size(); i++) { FixedWidthSchema.Field currentField = fields.get(i); int fieldLength = currentField.getFieldLength(); FieldAlignment currentFieldAlignment; if (currentField.getAlignment().equalsIgnoreCase("centre")) { currentFieldAlignment = FieldAlignment.CENTER; } else if (currentField.getAlignment().equalsIgnoreCase("left")) { currentFieldAlignment = FieldAlignment.LEFT; } else { currentFieldAlignment = FieldAlignment.RIGHT; } fieldWidthFields.addField(currentField.getName(), fieldLength, currentFieldAlignment, currentField.getPadding()); } FixedWidthParserSettings settings = new FixedWidthParserSettings(fieldWidthFields); univocityParser = new com.univocity.parsers.fixed.FixedWidthParser(settings); }
/** * Clones this configuration object to reuse most user-provided settings. This includes the fixed-width field configuration, * but doesn't include other input-specific settings. This method is meant to be used internally only. * * @return a copy of all configurations applied to the current instance. * * @deprecated doesn't really make sense for fixed-width. . Use alternative method {@link #clone(FixedWidthFields)}. */ @Deprecated protected final FixedWidthWriterSettings clone(boolean clearInputSpecificSettings) { return clone(clearInputSpecificSettings, fieldLengths == null ? null : fieldLengths.clone()); }
/** * Returns the sequence of field lengths to be written to form a record. * * @return the sequence of field lengths to be written to form a record. */ int[] getAllLengths() { if (fieldLengths == null) { return null; } return fieldLengths.getAllLengths(); }
/** * Adds the length of the next field in a fixed-width record. This method can be chained like this: addField("field_1", 5).addField("field_2", 6)... * * @param name the name of the next field. It is not validated. * @param length the length of the next field. It must be greater than 0. * * @return the FixedWidthFields instance itself for chaining. */ public FixedWidthFields addField(String name, int length) { return addField(name, length, FieldAlignment.LEFT, '\0'); }
/** * Function to create a univocity Parser */ private void createUnivocityParser() { List<FixedWidthSchema.Field> fields = schema.getFields(); FixedWidthFields fieldWidthFields = new FixedWidthFields(); for (int i = 0; i < fields.size(); i++) { FixedWidthSchema.Field currentField = fields.get(i); int fieldLength = currentField.getFieldLength(); FieldAlignment currentFieldAlignment; if (currentField.getAlignment().equalsIgnoreCase("centre")) { currentFieldAlignment = FieldAlignment.CENTER; } else if (currentField.getAlignment().equalsIgnoreCase("left")) { currentFieldAlignment = FieldAlignment.LEFT; } else { currentFieldAlignment = FieldAlignment.RIGHT; } fieldWidthFields.addField(currentField.getName(), fieldLength, currentFieldAlignment, currentField.getPadding()); } FixedWidthParserSettings settings = new FixedWidthParserSettings(fieldWidthFields); univocityParser = new com.univocity.parsers.fixed.FixedWidthParser(settings); }
/** * Creates a new instance initialized from {@link FixedWidth} annotations in the fields and methods of a given class. Note that * all fields should additionally have the {@link Parsed} annotation to configure header names and/or their positions. * * Only setter methods will be considered as fields. * * @param beanClass the class whose {@link FixedWidth} annotations will be processed to configure this field list. * * @return a new {@link FixedWidthFields} instance built with the {@link FixedWidth} annotations found in the given class' attributes and methods (excluding getters) */ public static FixedWidthFields forParsing(Class beanClass) { return new FixedWidthFields(beanClass, MethodFilter.ONLY_SETTERS); }
/** * Adds the length of the next field in a fixed-width record. This method can be chained like this: addField(5).addField(6)... * * @param length the length of the next field. It must be greater than 0. * @param padding the representation of unused space in this field * * @return the FixedWidthFields instance itself for chaining. */ public FixedWidthFields addField(int length, char padding) { return addField(null, length, FieldAlignment.LEFT, padding); }
//define field lengths FixedWidthFields fields = new FixedWidthFields(); accountFields.addField("ID", 10); accountFields.addField("Bank", 8); accountFields.addField("AccountNumber", 15); accountFields.addField("Swift", 12); //configure the parser FixedWidthParserSettings settings = new FixedWidthParserSettings(fields); //many options here, check the tutorial settings.getFormat().setLineSeparator("\n"); //We can now parse all rows FixedWidthParser parser = new FixedWidthParser(settings); List<String[]> rows = parser.parseAll(new File("/path/to/file.txt"));
/** * Adds the length of the next field in a fixed-width record. This method can be chained like this: addField(5).addField(6)... * * @param length the length of the next field. It must be greater than 0. * @param alignment the alignment of the field * @param padding the representation of unused space in this field * * @return the FixedWidthFields instance itself for chaining. */ public FixedWidthFields addField(int length, FieldAlignment alignment, char padding) { return addField(null, length, alignment, padding); }
// creates the sequence of field lengths in the file to be parsed FixedWidthFields fields = new FixedWidthFields(4, 5, 40, 40, 8); // creates the default settings for a fixed width parser FixedWidthParserSettings settings = new FixedWidthParserSettings(fields); // many settings here, check the tutorial. //sets the character used for padding unwritten spaces in the file settings.getFormat().setPadding('_'); // creates a fixed-width parser with the given settings FixedWidthParser parser = new FixedWidthParser(settings); // parses all rows in one go. List<String[]> allRows = parser.parseAll(new File("path/to/fixed.txt")));