我正在使用Jackson CSVMapper将一个制表符分隔的文本文件读取到java对象列表中,然后将其写回另一个制表符分隔的文本文件中。我的类看起来像这样:
@Getter
@Setter
@ToString
@NoArgsConstructor
@JsonPropertyOrder({
"Id",
"Name",
"Address 1",
"Address 2"})
public class InputSchema {
@JsonProperty("Id")private String id;
@JsonProperty("Name") private String name;
@JsonProperty("Address 1") private String address1;
@JsonProperty("Address 2") private String address2;
}
解析器代码:
public List<InputSchema> parseAddresses(String fileContent) throws IOException {
List<InputSchema> inputAddresses = new ArrayList<>();
InputStream inputStream = new ByteArrayInputStream(fileContent.getBytes());
MappingIterator<InputSchema> iterator = getInputSchemaMappingIterator(inputStream);
while (iterator.hasNextValue()) {
InputSchema inputAddress = iterator.nextValue();
log.info(inputAddress.toString());
inputAddresses.add(inputAddress);
}
return inputAddresses;
}
private MappingIterator<InputSchema> getInputSchemaMappingIterator(InputStream inputStream) throws IOException {
CsvMapper mapper = new CsvMapper();
mapper.configure(CsvParser.Feature.FAIL_ON_MISSING_COLUMNS, true);
mapper.configure(CsvParser.Feature.TRIM_SPACES, true);
CsvSchema schema = mapper.schemaFor(InputSchema.class)
.withColumnSeparator('t')
.withHeader()
.withStrictHeaders(true);
ObjectReader reader = mapper.readerFor(InputSchema.class).with(schema);
MappingIterator<InputSchema> iterator = reader.readValues(inputStream);
return iterator;
}
编写器代码:
private String toTxt(List<InputSchema> inputAddresses) throws JsonProcessingException {
CsvMapper mapper = new CsvMapper();
CsvSchema schema = mapper.schemaFor(InputSchema.class)
.withColumnSeparator('t')
.withLineSeparator("n")
.withHeader()
.withoutQuoteChar();
return mapper.writer(schema).writeValueAsString(inputAddresses);
}
我想只提取标题而不考虑数据。所以
String header = extractHeader();
应该返回
"IdtNametAddress 1tAddress 2"
我该怎么做?
谢谢!
这对
我有用。
public String extractHeader(CsvSchema schema) throws JsonProcessingException {
CsvSchema headerSchema = schema.withHeader();
return new CsvMapper().writer(headerSchema).writeValueAsString(null);
}
以下方法有效:
public static String displayHeader() {
CsvMapper mapper = new CsvMapper();
JavaType javaType = mapper.getTypeFactory().constructType(InputSchema.class);
BeanDescription beanDescription = mapper.getSerializationConfig().introspect(javaType);
List<BeanPropertyDefinition> properties = beanDescription.findProperties();
List<String> columnNames = properties.stream()
.map(e -> e.getName())
.collect(Collectors.toList());
String header = String.join("t", columnNames);
return header;
}
参考资料:@cassiomolin的答案