This commit is contained in:
Looly
2022-01-26 18:35:16 +08:00
parent f729ba7b9c
commit 54a6ba09c6
4 changed files with 24 additions and 11 deletions

View File

@@ -1,6 +1,7 @@
package cn.hutool.core.text.csv;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.ArrayIter;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.io.FileUtil;
@@ -45,6 +46,10 @@ public final class CsvWriter implements Closeable, Flushable, Serializable {
* 是否处于新行开始
*/
private boolean newline = true;
/**
* 是否首行即CSV开始的位置当初始化时默认为true一旦写入内容为false
*/
private boolean isFirstLine = true;
// --------------------------------------------------------------------------------------------------- Constructor start
@@ -183,13 +188,7 @@ public final class CsvWriter implements Closeable, Flushable, Serializable {
* @throws IORuntimeException IO异常
*/
public CsvWriter write(String[]... lines) throws IORuntimeException {
if (ArrayUtil.isNotEmpty(lines)) {
for (final String[] values : lines) {
appendLine(values);
}
flush();
}
return this;
return write(new ArrayIter<>(lines));
}
/**
@@ -320,9 +319,14 @@ public final class CsvWriter implements Closeable, Flushable, Serializable {
public CsvWriter writeComment(String comment) {
Assert.notNull(this.config.commentCharacter, "Comment is disable!");
try {
if(isFirstLine){
// 首行不补换行符
isFirstLine = false;
}else {
writer.write(config.lineDelimiter);
}
writer.write(this.config.commentCharacter);
writer.write(comment);
writer.write(config.lineDelimiter);
newline = true;
} catch (IOException e) {
throw new IORuntimeException(e);
@@ -366,12 +370,17 @@ public final class CsvWriter implements Closeable, Flushable, Serializable {
* @param fields 字段列表 ({@code null} 值会被做为空值追加)
* @throws IOException IO异常
*/
private void doAppendLine(final String... fields) throws IOException {
private void doAppendLine(String... fields) throws IOException {
if (null != fields) {
if(isFirstLine){
// 首行不补换行符
isFirstLine = false;
}else {
writer.write(config.lineDelimiter);
}
for (String field : fields) {
appendField(field);
}
writer.write(config.lineDelimiter);
newline = true;
}
}

View File

@@ -2,7 +2,6 @@ package cn.hutool.core.text.csv;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.CharsetUtil;
import org.junit.Ignore;
import org.junit.Test;
public class CsvWriterTest {
@@ -19,6 +18,8 @@ public class CsvWriterTest {
CharsetUtil.CHARSET_GBK, false, csvWriteConfig);
writer.writeHeaderLine("name", "gender", "address");
writer.writeLine("张三", "", "XX市XX区");
writer.writeLine("李四", "", "XX市XX区,01号");
writer.close();
}
}