什么是最简单的写作和写作方式将2D布尔数组读取到CSV文件?

时间:2015-06-18 19:07:44

标签: java arrays parsing csv

我想将一个2维布尔数组写入CSV文件。 我正在使用Apache Commons的CSVParser。问题是我无法找到一种内置的方法来将数组转换为可以写入CSV文件然后转换回来的内容。

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

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

感谢您的帮助。

3 个答案:

答案 0 :(得分:1)

我不知道这样做的内置方式,所以我的第一直觉是编写arrayToCsv方法和csvToArray方法。

arrayToCsv方法可能如下所示:

public String arrayToCsv(boolean[][] array) {
  String csv = "";
  for (int i = 0; i < array.length; i++) {
    for (int j = 0; j < array[i].length; j++) {
      csv = csv + array[i][j]; //java will autobox and convert this for you
      if (j == (array[i].length - 1))
        csv = csv + ",";
    }
    if (i == (array.length - 1))
      csv = csv + "\n";
  }
  return csv;
}

修改:更新了arrayToCsv方法以包含@Clashsoft的建议:

public String arrayToCsv(boolean[][] array) {
  int initialSize = array.length * array[0].length * 7; //longest possible string*
  StringBuilder csv = new StringBuilder(initialSize);
  for (int i = 0; i < array.length; i++) {
    for (int j = 0; j < array[i].length; j++) {
      csv.append(array[i][j]);
      if (j == (array[i].length - 1))
        csv.append(",");
    }
    if (i == (array.length - 1))
      csv.append("\n");
  }
  return csv.toString();
}

*注意:字符串的长度将始终在arraySize * len(&#34; true,&#34;)和arraySize * len(&#34; false,\ n&#34;)之间,尽管实际端点附近的长度可能很少见。我选择了尽可能长的大小来初始化StringBuilder,以通过防止它自己调整大小来优化效率。我认为浪费的空间通常会产生微不足道的影响。

相应的csvToArray方法是:

public boolean[][] csvToArray(String csv) {
  String[] rows = csv.split("\n");
  boolean[][] array = new boolean[rows.length][]; 
  int r = 0;
  for (String row : rows) {
    String[] temp = row.split(",");
    for (int i = 0; i < temp.length; i++)
      array[r][i] = Boolean.parseBoolean(temp[i]);
    r++;
  }
  return array;
}

我没有机会编译和运行这些,所以我无法做出任何保证。我回家后会这样做,如果有任何错误,我会进行编辑。希望这可以帮助;祝你好运!

答案 1 :(得分:1)

这是代码,适用于apache常见的CSV lib。

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;




public class Main {

    public static void main(String[] args) throws IOException {
        Appendable stream = new PrintWriter(new BufferedWriter(new FileWriter("foo.out")));
        CSVPrinter printer = new CSVPrinter(stream, CSVFormat.DEFAULT);
        boolean [][] data = new boolean[5][5];
        for (int i=0; i<5; i++){
            for (int j=0; j<5; j++){
                data[i][j] = i ==j;
                printer.print(data[i][j]);
            }
            printer.println();
        }
        printer.flush();
        printer.close();

    }

}

以下是它生成的输出:

true,false,false,false,false
false,true,false,false,false
false,false,true,false,false
false,false,false,true,false
false,false,false,false,true

我希望它有帮助=]

答案 2 :(得分:1)

使用uniVocity-parsers来写/读你的布尔值。

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]

注意:写作时不应该明确设置标题,但我只是在master branch of the project

中找到(并修复了)这个标题