java8实现:将List<ADto>出力成csv文件。参数为List<ADto>、ADto.class、filePath
时间: 2024-05-07 18:22:07 浏览: 8
可以使用 Java 8 中的 Stream API 和 Lambda 表达式,以及 OpenCSV 库来实现将 List<ADto> 输出成 CSV 文件。代码如下:
```java
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import com.opencsv.CSVWriter;
public class ListToCsvUtil {
public static void listToCsv(List<?> list, Class<?> clazz, String filePath) throws IOException {
// 创建 CSVWriter 对象
CSVWriter writer = new CSVWriter(new FileWriter(filePath));
// 获取表头
String[] header = clazz.getDeclaredFields()
.stream()
.map(field -> field.getName())
.toArray(String[]::new);
writer.writeNext(header);
// 写入数据
list.stream()
.map(item -> {
String[] row = new String[header.length];
for (int i = 0; i < header.length; i++) {
try {
row[i] = String.valueOf(clazz.getDeclaredField(header[i]).get(item));
} catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException e) {
e.printStackTrace();
}
}
return row;
})
.forEach(row -> writer.writeNext(row));
// 关闭资源
writer.flush();
writer.close();
}
}
```
使用方式如下:
```java
List<ADto> list = ... // 获取数据
String filePath = "/path/to/csv/file.csv";
ListToCsvUtil.listToCsv(list, ADto.class, filePath);
```
这样就可以将 `list` 中的数据输出成 CSV 文件了。注意,这里的 `ADto` 类需要有对应的 getter 方法,否则无法获取到字段的值。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)