java不能安装 com.opencsv.CSVWriter;
时间: 2024-03-14 11:49:23 浏览: 143
安装opencv时遇到的问题
如果您无法安装OpenCSV库,可以尝试使用Java自带的CSV库来读写CSV文件。以下是一个使用Java自带CSV库来写入CSV文件的示例代码:
```java
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class CSVWriterExample {
public static void main(String[] args) {
String csvFile = "output.csv";
FileWriter writer = null;
List<String[]> data = new ArrayList<String[]>();
data.add(new String[] {"id", "url", "title", "content"});
data.add(new String[] {"1", "http://www.example.com/1", "Title 1", "Content 1"});
data.add(new String[] {"2", "http://www.example.com/2", "Title 2", "Content 2"});
data.add(new String[] {"3", "http://www.example.com/3", "Title 3", "Content 3"});
data.add(new String[] {"4", "http://www.example.com/4", "Title 4", "Content 4"});
try {
writer = new FileWriter(csvFile);
for (String[] rowData : data) {
writer.append(String.join(",", rowData));
writer.append("\n");
}
System.out.println("CSV file written successfully.");
} catch (IOException e) {
System.out.println("Error in CSV file writing.");
e.printStackTrace();
} finally {
try {
writer.flush();
writer.close();
} catch (IOException e) {
System.out.println("Error while flushing/closing fileWriter.");
e.printStackTrace();
}
}
}
}
```
在上述代码中,我们使用List<String[]>来保存数据,然后在循环中遍历List,并使用String.join()方法将String数组中的元素以逗号分隔拼接成字符串,最后将字符串写入CSV文件中。需要注意的是,我们需要手动加上换行符来表示换行。此外,我们还需要在finally块中关闭writer对象,以确保文件被正确关闭。
阅读全文