【已解决】Android Studio 加载自定义properties文件出错java.lang.ExceptionInInitializerError Caused by: java.lang.Nu

Android Studio 在加载自定义properties配置文件时出错:

java.lang.ExceptionInInitializerError

Caused by: java.lang.NullPointerException


定位到出错的地方,源头是Properties类 对象的load()方法,该方法需要一个InputStream的参数

Properties p = new Properties(); 

... 

p.load(is);

文件是放在包根目录的,assets试过,项目根目录也试过,java根目录也试过,src根目录也试过

网上百度试过以下方法:

//视频中方法 
InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("com/example/app/db.properties");
//百度方法1:通过当前类加载器的getResourceAsStream方法获取 
InputStream is = DBUtils.class.getClassLoader().getResourceAsStream("com/example/app/db.properties");
//百度方法2:从文件方式获取 
InputStream is = null; 
try { 
    is = new FileInputStream(new File("com/example/app/db.properties")); 
} catch (FileNotFoundException e) { 
    e.printStackTrace(); 
}
//百度方法3:通过类加载器获取 
InputStream is = ClassLoader.getSystemResourceAsStream("com/example/app/db.properties");
//百度方法4:通过url获取 
InputStream is = null; 
try { 
    java.net.URL url = new URL("com/example/app/db.properties"); 
    is = url.openStream(); 
} catch (MalformedURLException e) { 
    e.printStackTrace(); 
} catch (IOException e) { 
    e.printStackTrace(); 
}

其他方法

InputStream is = context.getAssets().open("com/example/app/db.properties");
InputStream is = getResources().openRawResource(R.raw.app);
InputStream is = DBUtils.class.getResourceAsStream("com/example/app/db.properties");

最后想到需要InputStream类型的对象,传入它的子类应该也是可以的吧,

然后用绝对路径传入:

InputStream is = new FileInputStream("C:\\Users\\Admin\\Desktop\\db.properties");

结果成了!

绝对路径太费劲,想换相对路径,使用

System.out.println(System.getProperty("user.dir"));

输出当前项目所在文件夹路径

C:\Users\Admin\AndroidStudioProjects\App

原来如此!

接下来替换成相对路径:

InputStream is = new FileInputStream(".\\app\\src\\main\\java\\com\\example\\app\\db.properties");

Over!

PS:

直接使用InputStream的方式没有成功,不知道问题出现在哪里,望路过大佬不吝赐教!

发布了10 篇原创文章 · 获赞 14 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_32682301/article/details/100552540