使用Java的反射机制时,这就需要使用Class.forName()方法。使用该方法需要读取properties文件,继而需要创建流,而创建流就需要获取文件读取地址。而使用上述方法创建地址时报错,分析错误发现,地址有问题,获取的地址中出现了乱码,继续测试,发现只要地址中出现中文或者特殊字符就会出现该问题。
String path=Thread.currentThread().getContextClassLoader().getResource("jdbc.properties").getPath();
Exception in thread "main" java.io.FileNotFoundException: F:\%e5%b7%a5%e4%bd%9c\cs%e8%87%aa%e5%ad%a6%e8%b5%84%e6%96%99\java\javaSE\ideaPracticeCode\out\production\ideaPracticeCode\ppp.properties (系统找不到指定的路径。)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileInputStream.<init>(FileInputStream.java:93)
at java.io.FileReader.<init>(FileReader.java:58)
at com.practice.IO.PropertiesTest.main(PropertiesTest.java:14)
解决方法
1.第一种方法,直接通过转为获得字节流的方法
InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("jdbc.properties")
2.通过资源绑定器解决
ResourceBundle rb = ResourceBundle.getBundle("jdbc");
完美解决