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.

69 lines
2.7 KiB

package util;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import model.Article;
public class FileUtil {
private static final String DATA_DIR = "data";
static {
File dir = new File(DATA_DIR);
if (!dir.exists()) {
dir.mkdirs();
}
}
public static void saveArticle(Article article) throws IOException {
String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String filename = DATA_DIR + "/" + article.getSource() + "_" + timestamp + ".txt";
try (BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(filename), "UTF-8"))) {
writer.write("========================================\n");
writer.write("来源:" + article.getSource() + "\n");
writer.write("标题:" + article.getTitle() + "\n");
writer.write("链接:" + article.getUrl() + "\n");
writer.write("时间:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "\n");
writer.write("========================================\n");
writer.write("内容:\n");
writer.write(article.getContent() != null ? article.getContent() : "无内容");
writer.write("\n");
}
}
public static void saveArticles(List<Article> articles, String filename) throws IOException {
String filepath = DATA_DIR + "/" + filename;
try (BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(filepath), "UTF-8"))) {
writer.write("爬取结果汇总\n");
writer.write("时间:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "\n");
writer.write("数量:" + articles.size() + "\n");
writer.write("========================================\n\n");
for (int i = 0; i < articles.size(); i++) {
Article article = articles.get(i);
writer.write("【" + (i + 1) + "】\n");
writer.write("来源:" + article.getSource() + "\n");
writer.write("标题:" + article.getTitle() + "\n");
writer.write("链接:" + article.getUrl() + "\n");
writer.write("\n");
}
}
}
public static List<String> listSavedFiles() {
File dir = new File(DATA_DIR);
File[] files = dir.listFiles((d, name) -> name.endsWith(".txt"));
List<String> result = new ArrayList<>();
if (files != null) {
for (File file : files) {
result.add(file.getName());
}
}
return result;
}
}