1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > 关于在IDEA的Resources目录下无法加载文件的问题

关于在IDEA的Resources目录下无法加载文件的问题

时间:2019-05-24 20:05:17

相关推荐

关于在IDEA的Resources目录下无法加载文件的问题

我的目录结构

使用绝对路径加载

Properties p = new Properties();InputStream in = null;try {//用绝对路径加载File file =new File("C:\\Users\\Plory\\IdeaProjects\\a\\src\\main\\java\\package2\\p2.properties");in = new FileInputStream(file);p.load(in);System.out.println("username="+p.getProperty("username"));} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}

通过Class.getResourceAsStream(String path)加载

Properties p = new Properties();//从classpath根目录下加载文件//InputStream in = package2.Test.class.getClassLoader().getResourceAsStream("p2.properties");//path不以“/”开头时,默认是从当前类所在的包下面获取资源//InputStream in = Test.class.getResourceAsStream("p2.properties");//path以“/”开头时,则是从项目的classPath根下获取资源InputStream in = Test.class.getResourc![在这里插入图片描述](https://img-/0314185028945.PNG?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzM3OTYyNzE0,size_16,color_FFFFFF,t_70)eAsStream("/package2/p2.properties");p.load(in);System.out.println("username="+p.getProperty("username"));

通过ClassLoader.getResourceAsStream(String path)加载

public class Test {public static void main(String[] args) throws IOException {Test test = new Test();Properties p = new Properties();//默认是从classpath根下获取,path不能以“/”开头InputStream in = test.getClass().getClassLoader().getResourceAsStream("package2/p2.properties");p.load(in);System.out.println("username="+p.getProperty("username"));}}

getResourceAsStream方法读取的文件路径只局限与工程的源文件夹中(包括在工程src根目录下,以及类包里面任何位置),但是如果配置文件路径是在除了源文件夹之外的其他文件夹中时,该方法是用不了的。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。