使用我在这里找到的答案,我发现了一种将结果集写入csv文件的方法。但是,它目前只是将数组的每个元素写入新列。我如何更改以下代码以更改格式以在每个第x个元素上创建新行?如下所示?
int value = 2
Current format: a, b, c, d, e, f
Desired format: a, b,
c, d,
e, f
我知道我可以利用int值的模数,但不确定如何写入特定的列或行。
private static final String DEFAULT_SEPARATOR = " ";
public static void writeLine(Writer w, List<String> values, String separators, String customQuote) throws IOException {
boolean first = true;
//default customQuote is empty
if (separators == " ") {
separators = DEFAULT_SEPARATOR;
}
StringBuilder sb = new StringBuilder();
for (String value : values) {
if (!first) {
sb.append(separators);
}
if (customQuote == " ") {
sb.append(followCVSformat(value));
} else {
sb.append(customQuote).append(followCVSformat(value)).append(customQuote);
}
first = false;
}
sb.append("\n");
w.append(sb.toString());
}
private static String followCVSformat(String value) {
String result = value;
if (result.contains("\"")) {
result = result.replace("\"", "\"\"");
}
return result;
}
答案 0 :(得分:0)
public static void writeLine(
Writer w, List<String> values, String separators, String customQuote, int elementsPerRow)
throws IOException {
...
int counter = 0;
for (String value : values) {
if (!first) {
sb.append(separators);
}
if (counter != 0 && counter % elementsPerRow == 0)
sb.append("\n");
if (customQuote == " ") {
sb.append(followCVSformat(value));
} else {
sb.append(customQuote).append(followCVSformat(value)).append(customQuote);
}
first = false;
counter++;
}
...