java 怎么保存csv文件
时间: 2023-09-25 13:12:18 浏览: 40
Java可以使用CSV格式的文件进行数据存储和交换。下面是一些保存CSV文件的示例代码:
1. 使用CSVWriter类
```java
import java.io.FileWriter;
import java.io.IOException;
import com.opencsv.CSVWriter;
public class CSVWriterExample {
public static void main(String[] args) throws IOException {
String csvFile = "output.csv";
CSVWriter writer = new CSVWriter(new FileWriter(csvFile));
String[] data = {"John", "Doe", "35"};
writer.writeNext(data);
writer.close();
}
}
```
2. 手动写入文件
```java
import java.io.FileWriter;
import java.io.IOException;
public class CSVFileWriter {
public static void main(String[] args) throws IOException {
String csvFile = "output.csv";
FileWriter writer = new FileWriter(csvFile);
writer.append("Name");
writer.append(",");
writer.append("Age");
writer.append("\n");
writer.append("John");
writer.append(",");
writer.append("35");
writer.append("\n");
writer.flush();
writer.close();
}
}
```
无论你选择哪种方法,都需要在代码中指定CSV文件的路径和文件名。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)