解決 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");  中寫到具體路徑

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM