gpt4 book ai didi

java - 将二维 boolean 数组写入和读取 CSV 文件时最简单的方法是什么?

转载 作者:行者123 更新时间:2023-11-29 05:04:23 25 4
gpt4 key购买 nike

我想将二维 boolean 数组写入 CSV 文件。我正在使用 Apache Commons 的 CSVParser。问题是我找不到将数组转换为可以写入 CSV 文件然后再转换回来的东西的内置方法。

那么除了使用 Arrays.deepToString(...) 之外还有其他方法吗?然后写一个复杂且容易出错的函数来解析数组?

如果boolean[][] array = Arrays.parse<boolean[][]>(Arrays.deepToString(oldArray))就好了存在...

感谢您的帮助。

最佳答案

使用uniVocity-parsers写/读你的 boolean 值。

public static void main(String ... args){
CsvWriterSettings writerSettings = new CsvWriterSettings();

ObjectRowWriterProcessor writerProcessor = new ObjectRowWriterProcessor(); // handles rows of objects and conversions to String.
writerProcessor.convertAll(Conversions.toBoolean("T", "F")); // will write "T" and "F" instead of "true" and "false"

writerSettings.setRowWriterProcessor(writerProcessor);

CsvWriter writer = new CsvWriter(writerSettings);
writerSettings.setHeaders("A", "B", "C", "D");

String line1 = writer.processRecordToString(true, false, false, true);
String line2 = writer.processRecordToString(false, false, true, true);

System.out.println("### Rows written ###");

System.out.println(line1);
System.out.println(line2);

// Now, let's read these lines

CsvParserSettings parserSettings = new CsvParserSettings();

ObjectRowListProcessor readerProcessor = new ObjectRowListProcessor(); // handles conversions from String to Objects and adds the result to a list
readerProcessor.convertAll(Conversions.toBoolean("T", "F")); //reads "T" and "F" back to true and false

parserSettings.setRowProcessor(readerProcessor);

CsvParser parser = new CsvParser(parserSettings);
parser.parseLine(line1); //handled by the readerProcessor
parser.parseLine(line2); //handled by the readerProcessor

System.out.println("### Rows parsed ###");

List<Object[]> rows = readerProcessor.getRows();
for(Object[] row : rows){
System.out.println(Arrays.toString(row));
}
}

上面的代码产生:

### Rows written ###
T,F,F,T
F,F,T,T
### Rows parsed ###
[true, false, false, true]
[false, false, true, true]

注意:您在编写时不需要显式设置 header ,但我刚刚在 master branch of the project 中找到(并修复)了它

关于java - 将二维 boolean 数组写入和读取 CSV 文件时最简单的方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30923753/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com