![](/img/trans.png)
[英]Export 2-D object array (Object[][] array) into a .csv file in Java
[英]Export array values to csv file java
我只需要幫助將數組元素導出到csv文件。 我不知道我的代碼有什么問題。 任何幫助都很高興。 謝謝。
for (int index = 0; index < cols.length; index++)
{
FileWriter fw = new FileWriter(newFileName);
if (index == cols.length - 1)
{
fw.append(cols[index]);
}
else
{
fw.append(cols[index]);
fw.append(",");
}
}
當我跑這個。 我的csv文件沒有任何反應。 事實上,它抹去了一切。 請幫忙。
假設您在陣列中存儲String,我發布了一個替代解決方案:
BufferedWriter br = new BufferedWriter(new FileWriter("myfile.csv"));
StringBuilder sb = new StringBuilder();
// Append strings from array
for (String element : array) {
sb.append(element);
sb.append(",");
}
br.write(sb.toString());
br.close();
最好的祝福。
finally {
fw.close(); // close will automatically flush the data
}
此外,使用BufferedWriter或PrintWriter,因為它們比FileWriter高效和進化。
順便說一句,聲明FileWriter超出你的for循環。 目前,它將覆蓋每次迭代的列。
如果您使用更有效的BufferedWriter與try-with-resources相結合,則編寫器將自動關閉。 (在Java 7中)
try {BufferedWriter br = new BufferedWriter(new FileWriter(newFileName)) {
// your code
}
你必須使用
FileWriter fw = new FileWriter(newFileName,true);
附加內容,否則文件將被覆蓋。
append
方法的名稱可能會產生誤導,實際上它附加到內部緩沖區,而不是文件內容。
最好的方法是使用CSVWriter。 如果您有maven項目,請將其添加為依賴項:
<dependency>
<groupId>com.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>4.4</version>
</dependency>
然后你可以像這樣使用它:
try {
//the list that contains the String arrays
List<String[]> whatever = new ArrayList<>();
CSVWriter writer = new CSVWriter(new FileWriter(csvFilename));
String[] header = "Name,Age,Height,etc..".split(",");
writer.writeNext(header);
writer.writeAll(whatever, true); //And the second argument is boolean which represents whether you want to write header columns (table column names) to file or not.
writer.close();
System.out.println("CSV file created succesfully.");
} catch (Exception e) {
System.out.println("exception :" + e.getMessage());
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.