zoukankan      html  css  js  c++  java
  • 解决 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");  中写到具体路径

  • 相关阅读:
    MySQL涉及连接的问题
    SQL注入的问题
    如果有一个特别大的访问量到数据库上,怎么做优化?主从复制、读写分离
    MySQL,优化查询的方法
    Solr搜索引擎
    线程安全与锁优化
    Java与线程
    Java内存模型
    你不会成为数据科学家的9个原因:数据科学是一个艰难的领域,请做好准备
    深度学习中的激活函数完全指南:在数据科学的诸多曲线上进行现代之旅
  • 原文地址:https://www.cnblogs.com/itcod/p/12984668.html
Copyright © 2011-2022 走看看