项目场景:
获取Java项目中的docx、ftl等文档模板,利用freemarker渲染文档,并生成docx文档,再转为pdf,以流的形式或byte[]转base64字符串的形式返给页面下载。
问题描述
开发环境使用的是tomcat服务器,应用启动后一切正常;
发布测试环境使用的是weblogic服务器,发现File类读取docx和ftl模板,无法找到文件(路径错误)。
File docxFile = new File(temp_path+docxTemplate);
if(!docxFile.exists()){
throw new AppException("未获取到【"+docxTemplate+"】!");
}
原因分析:
提示:这里填写问题的分析:
tomcat 和 weblogic 的发布方式不同,tomcat将war包解析后class文件是存放在classes文件夹下的,目录结构和项目中src是一致的,这时用类加载器可以获取其相对地址。
String classPath = Thread.currentThread().getContextClassLoader().getResource("/").getPath();
而weblogic部署后,发现classes目录下是空的,这是因为weblogic会将class文件重新打包后放在 WEB_INFO 的lib下。
//打印输出/wordFile文件夹路径(docx在该文件夹下)和/路径
String wordFilePath = Thread.currentThread().getContextClassLoader().getResource("/wordFile").getPath();
String classPath = Thread.currentThread().getContextClassLoader().getResource("/").getPath();
输出为:
/home/weblogic/Middleware/user_projects/domains/xxxx_domain/servers/xxx/tmp/_WL_user/xxxxxxx/ca08kq/war/WEB-INF/lib/_wl_cls_gen.jar!/wordFile
-------------------------------------------
/home/weblogic/Middleware/user_projects/domains/xxxx_domain/servers/xxx/tmp/_WL_user/xxxxxxx/ca08kq/war/WEB-INF/classes/
解决方案:
提示:这里填写该问题的具体解决方案:
两种解决方案:
第一种:文件在resource资源目录下,以流的形式读取文件并在classes目录下创建该文件(第一次运行时创建),之后正常路径在classes中读取文件。如果你只想获取流,可以直接获取,我是因为必须用到File对象,所以需要创建文件。
InputStream docxIs = Thread.currentThread().getContextClassLoader().getResourceAsStream("wordFile" + File.separator + docxName + ".docx");
String dname = docxName + ".docx";
InputStream ftlIs = Thread.currentThread().getContextClassLoader().getResourceAsStream("wordFile" + File.separator + docxName + ".ftl");
String fname = docxName + ".ftl";
try {
inputStream2file(docxIs,docxPath,dname);
inputStream2file(ftlIs,docxPath,fname);
} catch (IOException e) {
logger.error("classes中创建文件异常——" + e.getMessage());
}
public void inputStream2file(InputStream input,String path,String name) throws IOException {
File file=new File(path + name);
if(!file.exists()){
file.getParentFile().mkdirs();
file.createNewFile();
}else {
return;
}
BufferedInputStream in=null;
BufferedOutputStream out=null;
in=new BufferedInputStream(input);
out=new BufferedOutputStream(new FileOutputStream(fileName));
int len=-1;
byte[] b=new byte[1024];
while((len=in.read(b))!=-1){
out.write(b,0,len);
}
in.close();
out.close();
}
第二种:(最后项目中用的这种方法)将文件放到webapp 目录下,可以直接获取文件路径。
String classPath = Thread.currentThread().getContextClassLoader().getResource("/").getPath();
String basePath = "";
//window下
if("\\".equals(File.separator)){
basePath = classPath.substring(1,classPath.indexOf("WEB-INF/classes"));
basePath = basePath.replace("/","\\");
}
//linux下
if("/".equals(File.separator)){
basePath = classPath.substring(0,classPath.indexOf("WEB-INF/classes"));
basePath = basePath.replace("\\","/");
}
String docxPath = basePath + "wordFile" + File.separator;
一番波折,也是我学艺不精,类加载器的getResource()我以为只能获取resource资源目录下的文件,经领导点拨,原来在webapp下也可以获取到,而且还不会放到classes中。