解决 Java FileNotFoundException 异常
1、错误场景
_| src
_| cn.itcod
_| test
_| inflection
_| inflectionTest.java
_| application.txt
package cn.itcod.test.inflection; import cn.itcod.test.collection.test.CloneablePojo; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Properties; public class ClassName { public static void main(String[] args) throws Exception { Class<?> c = Class.forName(getValue("classpath")); System.out.println(c.getName()); CloneablePojo cloneablePojo = (CloneablePojo) c.newInstance(); Field field = c.getDeclaredField("info"); Method method = c.getMethod("setNo", int.class, String.class); Method method1 = c.getDeclaredMethod("getNo"); field.setAccessible(true); field.set(cloneablePojo, "'success' by field.set() set value"); method.invoke(cloneablePojo, 1, "method.invoke()"); System.out.println(field.get(cloneablePojo)); System.out.println(method1.invoke(cloneablePojo)); } public static String getValue(String key) throws IOException { Properties pro = new Properties();//获取配置文件的对象 FileReader in = new FileReader("application.txt");//获取输入流 pro.load(in);//将流加载到配置文件对象中 in.close(); return pro.getProperty(key);//返回根据key获取的value值 } }
用下面的代码测试和结果发现是在和 src 在一个层级
_| src
application.txt
_| cn.itcod
_| test
_| inflection
inflectionTest.java
application.txt
File file = new File("application"); if(!file.exists()){ //先得到文件的上级目录,并创建上级目录,在创建文件 try { //创建文件 file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } }
2、解决方法
从顶级路径书写到所在文件路
例如:这里我要是在 src/cn/itcod/test/inflection/application.txt
所以在 FileReader in = new FileReader("application.txt"); 中写到具体路径