You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

49 lines
1.8 KiB

package com.example.datacollect.persist;
import com.example.datacollect.model.Article;
import com.example.datacollect.repository.ArticleRepository;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
public class JsonExporter {
private static final Logger logger = LoggerFactory.getLogger(JsonExporter.class);
private final ObjectMapper objectMapper;
public JsonExporter() {
// 初始化Jackson,支持LocalDateTime序列化
this.objectMapper = new ObjectMapper();
objectMapper.registerModule(new JavaTimeModule());
objectMapper.enable(com.fasterxml.jackson.databind.SerializationFeature.INDENT_OUTPUT); // 美化JSON
}
/**
* 导出文章到JSON文件
* @param repository 文章仓库
* @param filePath 导出路径(如:articles.json)
*/
public void export(ArticleRepository repository, String filePath) throws IOException {
logger.info("开始导出文章到文件: {}", filePath);
List<Article> articles = repository.getAll();
if (articles.isEmpty()) {
logger.warn("仓库无文章,跳过导出");
return;
}
// try-with-resources 自动关闭FileWriter,避免资源泄漏
try (FileWriter writer = new FileWriter(new File(filePath))) {
objectMapper.writeValue(writer, articles);
logger.info("成功导出 {} 篇文章到: {}", articles.size(), filePath);
} catch (IOException e) {
logger.error("导出失败: {}", filePath, e);
throw e;
}
}
}