java的Properties类的路径问题

这个代码不一定能运行成功,可能会报找不到文件,因为程序只会找classpath路径的下的文件。 


    public static String getPath5() {
        InputStream in = LoadPropertiesFileUtil.class.getClassLoader()
                .getResourceAsStream("com/test/modul/utils/prop.properties");
        Properties p = new Properties();
        try {
            p.load(in);
            path = p.getProperty("path");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return path;

把InputStream实例in改为从FileInputStream中读取即可解决从任意位置读取文件。


    public static String getPath5() {
        InputStream in = new FileInputStream("../utils/prop.properties");
        Properties p = new Properties();
        try {
            p.load(in);
            path = p.getProperty("path");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return path;

你可能感兴趣的:(java)