java Spring Batch FlatFileItemWriter -输出自定义

zy1mlcev  于 2023-04-28  发布在  Java
关注(0)|答案(2)|浏览(142)

我需要生成具有以下要求的CSV文件:

  • 每个字段都用双引号括起来
  • 双引号用反斜杠转义
  • 反斜杠用反斜杠转义

输入:

  • 现场1
  • Field2带\反斜杠“双引号“和|烟斗
  • 现场3

预期输出:

"Field1"|"Field2With\\Backslash\"DoubleQuotes\"And|Pipe"|"Field3"

有可能获得这样的输出吗?

yeotifhr

yeotifhr1#

基本上,您只需要在编写字段之前对其进行处理。你可以用这两种方法
假设此方法处理您的字段

public String escape(String str) {
    str = "\"" + str + "\"";
    str = str.replace("|", "\\|");
    str = str.replace("\\", "\\\\");
    return str;
}

1 -在处理器期间处理-首选

@Override
public A process(B b) throws Exception {
    A a = new A();
    //Process b to a...    

    a.setField1(escape(a.getField1)); //For each fields
    return a;
}

2 -在自定义Writer中写入前处理

public class EscapeFlatFileItemWriter<A> extends FlatFileItemWriter<A> {

    @Override
    public void write(List<? extends A> items) throws Exception {
        for (A a : items) {
            a.setField1(escape(a.getField1)); //For each fields
        }
        super.write(items);
    }
}
whlutmcx

whlutmcx2#

public final class CustomDelimitedLineAggregator<T> extends ExtractorLineAggregator<T> {
private String delimiterChar = ",";
private String quoteChar = "\"";
private String escapeChar = "\\";

public CustomDelimitedLineAggregator() {
}

public CustomDelimitedLineAggregator(String delimiterChar) {
    this.delimiterChar = delimiterChar;
}

// getters and setters..

@Override
public String doAggregate(Object[] fieldList) {
    if (isEmpty(fieldList)) {
        return quote("");
    }

    if (fieldList.length == 1) {
        return quote(escape((valueOf(fieldList[0]))));
    }

    String aggregated = "";
    for (int i = 0; i < fieldList.length; i++) {
        if (i > 0) {
            aggregated += delimiterChar;
        }
        String field = valueOf(fieldList[i]);
        aggregated+=(quote(escape(field)));
    }
    return aggregated;
}

public String doAggregate(List<String> fieldList) {
    if (isEmpty(fieldList)) {
        return doAggregate((Object[]) null);
    }
    return doAggregate(fieldList.toArray(new Object[0]));
}

private String escape(String s) {
    if (s == null) {
        return null;
    }
    return s.replace(escapeChar, escapeChar + escapeChar)
            .replace(quoteChar, escapeChar + quoteChar);
}

private String quote(String s) {
    if (s == null) {
        return quoteChar + quoteChar;
    }
    return quoteChar + s + quoteChar;
}

}

相关问题