java - 使用 OpenCSV 写入列而不是行

标签 java csv text io opencsv

我有一个一维数组 String[],我想将其写入 CSV 文件,然后在 Excel 等电子表格程序中查看。但是,该数组的大小/长度太大,无法容纳允许的列数,但又足够小,足以容纳允许的行数。

那么,如何按列而不是按行写入?

我当前使用的代码:

import au.com.bytecode.opencsv.CSVWriter;

public class test {
    public static void main(String[] args) [
        CSVWriter writer2 = new CSVWriter(new FileWriter("testing.csv"), '\t');

        String[] string = new String[10];
        for(int i = 0; i < 10; i++) {
            string[i] = "Testing";
        }

        writer2.writeNext(string); //  !!EXPORTS AS ROW AND NOT A COLUMN!! //
        writer2.close();




    }
}

最佳答案

要将 String[] 写入文件,每个字符串位于单独的行中,您不需要 CSVWriter...普通旧 FileOutputStream会做

public static class test {
  public static void main(String[] args) throws UnsupportedEncodingException, IOException {
    String[] strings = new String[10];
    for (int i = 0; i < 10; i++) {
      strings[i] = "Testing";
    }

    OutputStream output = new FileOutputStream("testing.csv");
    try {
      for (String s : strings) {
        output.write(s.getBytes("UTF-8")); // don't rely on default encoding!
      }
    }
    finally {
      output.close();
    }
  }
}

但是,如果您确实想使用 CSVWriter 进行编写:

public static class test {
  public static void main(String[] args) throws UnsupportedEncodingException, IOException {
    CSVWriter writer2 = new CSVWriter(new FileWriter("testing.csv"), '\t');

    String[] strings = new String[10];
    for (int i = 0; i < 10; i++) {
      strings[i] = "Testing";
    }

    String[] wrap = new String[1]; //probably saving on GC

    for (String s: strings) {
      wrap[0]=s;
      writer2.writeNext(wrap);
    }
    writer2.close();

  }

}

关于java - 使用 OpenCSV 写入列而不是行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18785559/

相关文章:

python - ocr'ing 应用程序文本(未扫描,不是验证码)

java - XOM 元素子类的 equals()

java - 如何在 JasperReports 中显示 JTable 数据

javascript - 无输出 fast-csv writeToPath

html - 如何将 HTML 表格转换为 CSV?

java - 提高解析文本文件的性能

java - 一对一用户 Jhipster 关系

java - 从 PHP 到 Java。有什么建议吗?

python - 如何在 Pandas 的 .csv 文件中写入 DataFrame 时删除索引列?

java - 如何在 JLabel 中使字母的宽度相同?