gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 07:24:24 25 4
gpt4 key购买 nike

我有一个一维数组 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/

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