|
package com.example.skills.impl;
import com.example.skills.Skill;
import com.example.skills.SkillResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* 文件读取技能
* 用于读取本地文件内容
* @version 1.0.0
*/
public class FileReadSkill implements Skill {
private static final Logger logger = LoggerFactory.getLogger(FileReadSkill.class);
@Override
public String getName() {
return "FileReadSkill";
}
@Override
public String getDescription() {
return "读取本地文件内容,支持文本文件、配置文件等";
}
@Override
public boolean canExecute(String task) {
if (task == null) {
return false;
}
String lowerTask = task.toLowerCase();
return lowerTask.contains("文件") &&
(lowerTask.contains("读取") || lowerTask.contains("打开") || lowerTask.contains("查看"));
}
@Override
public boolean validate(String task, Map<String, Object> parameters) {
if (!Skill.super.validate(task, parameters)) {
return false;
}
// 检查文件路径参数
Object filePath = parameters.get("filePath");
if (filePath == null) {
logger.warn("filePath parameter is missing");
return false;
}
Path path = Paths.get(filePath.toString());
if (!Files.exists(path)) {
logger.warn("File does not exist: {}", filePath);
return false;
}
if (!Files.isReadable(path)) {
logger.warn("File is not readable: {}", filePath);
return false;
}
return true;
}
@Override
public SkillResult execute(String task, Map<String, Object> parameters) {
long startTime = System.currentTimeMillis();
try {
String filePath = parameters.get("filePath").toString();
logger.info("Reading file: {}", filePath);
Path path = Paths.get(filePath);
// 读取文件内容
String content = new String(Files.readAllBytes(path), StandardCharsets.UTF_8);
// 获取文件信息
long fileSize = Files.size(path);
String fileName = path.getFileName().toString();
// 构建元数据
Map<String, Object> metadata = new java.util.HashMap<>();
metadata.put("filePath", filePath);
metadata.put("fileName", fileName);
metadata.put("fileSize", fileSize);
metadata.put("lines", content.split("\n").length);
long executionTime = System.currentTimeMillis() - startTime;
logger.info("File read successfully: {} ({} bytes)", fileName, fileSize);
return SkillResult.success(
"文件读取成功: " + fileName,
content,
executionTime,
metadata
);
} catch (IOException e) {
logger.error("Error reading file", e);
return SkillResult.failure("文件读取失败: " + e.getMessage(), e.getMessage());
}
}
@Override
public long getTimeout() {
return 10000; // 10秒超时
}
/**
* 读取文件行
*/
public List<String> readLines(String filePath) throws IOException {
Path path = Paths.get(filePath);
return Files.readAllLines(path, StandardCharsets.UTF_8);
}
/**
* 检查文件是否存在
*/
public boolean exists(String filePath) {
return Files.exists(Paths.get(filePath));
}
/**
* 获取文件大小
*/
public long getFileSize(String filePath) throws IOException {
return Files.size(Paths.get(filePath));
}
}
|