@Override
public TemplateFile findByPath(String path) {
File file = new File(path);
if (!file.exists()) {
throw new SystemException("模板不存在请检查!");
String parentPath = null;
String[] fileParent = file.getParent().split("templates");
if (fileParent.length == 1){
parentPath = File.separator;
}else {
parentPath = fileParent[1];
TemplateFile templateFile = new TemplateFile();
templateFile.setFileName(file.getName());
templateFile.setFilePath(file.getAbsolutePath());
templateFile.setParentPath(parentPath);
// 这里是读取文件的内容,用到了下面写的方法,方法内有读写的文件流
templateFile.setContent(this.readTemplateFileContent(file));
return templateFile;
@Override
public String readTemplateFileContent(File file) {
ByteArrayOutputStream bos = null;
InputStream inputStream = null;
try {
inputStream = new FileInputStream(file);
byte[] buffer = new byte[1024];
int len;
bos = new ByteArrayOutputStream();
while ((len = inputStream.read(buffer)) != -1) {
bos.write(buffer, 0, len);
} catch (Exception e) {
throw new SystemException(e.getMessage());
} finally {
try {
if (bos != null) {
bos.close();
} catch (IOException e) {
log.error("读取模板失败");
// 当时删除不成功的原因就是没有下面的try...catch代码块,inputStream没有关闭
try {
inputStream.close();
} catch (IOException e) {
log.error("读取模板失败, {}", e);
try {
return new String(bos.toByteArray(), "utf-8");
} catch (UnsupportedEncodingException e) {
log.error("读取模板失败");
return "";