解决 Java FileNotFoundException
解决 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"); 中写到具体路径
本文作者:有间猫
本文链接:https://www.cnblogs.com/itcod/p/12984668.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步