Java——路径相关
异常描述:
java.io.FileNotFoundException: \com\swing\template\dao\Dao.tpl (系统找不到指定的路径。)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at com.swing.utils.ProjectUtils.readFileToSB(ProjectUtils.java:50)
at com.swing.chain.fileHandler.DaoFileHandler.readFromFile(DaoFileHandler.java:20)
at com.swing.chain.fileHandler.AbstractFileHandler.handler(AbstractFileHandler.java:32)
at com.swing.chain.fileHandler.FileHandlerChain.handle(FileHandlerChain.java:24)
at com.swing.frame.MainFrame$1$1.run(MainFrame.java:184)
...
相关代码:
目录结构:
工程代码:
// main函数 中初始化路径方法
private void initTplPath(ReplaceBean rb) throws URISyntaxException {
rb.setCtlTplPath("/com/swing/template/controller/Controller.tpl");
rb.setSerTplPath("/com/swing/template/service/Service.tpl");
rb.setSerImplTplPath("/com/swing/template/service/ServiceImpl.tpl");
rb.setDaoTplPath("/com/swing/template/dao/Dao.tpl");
}
//ReplaceBean 实体类中只含有常规get/set方法未进行其他处理,不作展示
// ControllerFileHander 中读取文件方法
@Override
public void readFromFile(ReplaceBean rb) {
String actionTplPath = rb.getCtlTplPath();
StringBuilder sb = ProjectUtils.yui.readFileToSB(actionTplPath); //异常
rb.setContent(sb);
}
//ProjectUtils 中读取资源方法
public StringBuilder readFileToSB(String filePath){
StringBuilder sb = new StringBuilder();
InputStream is = this.getClass().getResourceAsStream(filePath); //null
InputStreamReader isr = null;
BufferedReader br = null;
try {
if(null == is){
is = new FileInputStream(new File(filePath)); //异常
}
...
...
} catch (Exception e) {
e.printStackTrace();
};
}
触发原因:路径问题(确信)
第一反应是路径问题,网上摆渡了很多也大多都是路径有误所造成的,基本是没跑了,
但是问题就在于这个路径上,相对路径总是找不到资源换成绝对路径就可以了说明逻辑代码部分应该没有什么问题
还有一点就是当初上一个maven项目结束,建立这个项目时忘改顺手也使用了maven,感觉可能有影响
解决方案:使用绝对路径(暂时)
考虑到这个小工程后面可能要变为exe可执行文件,即环境随时发生变动,使用绝对路径肯定不好,因为时间紧迫,为了让整个工程先跑起来方便其他功能的开发只好治标不治本了(X),问题还在研究,正在考虑换个普通的java基础工程不交由maven管理试试