美文网首页
java读取Resources下文件及任意位置文件

java读取Resources下文件及任意位置文件

作者: 香山上的麻雀 | 来源:发表于2019-10-16 13:13 被阅读0次

1.从文件系统中读(配置文件位置随意指定)

Properties p = new Properties();
p.load(new FileInputStream("D://Mycode//pro.properties"));
String es_node = p.getProperty("es.node");

2.从类路径的resources下读

ResourceBundle bundle = ResourceBundle.getBundle("config");
String url = bundle.getString("url");

该方法默认读取的是resources文件夹下的以.properties为后缀的文件,代码中的例子即为config.properties

InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("ipConfig.properties");   
  Properties p = new Properties();   
  try {   
   p.load(inputStream);   
  } catch (IOException e1) {   
   e1.printStackTrace();   
  }   
System.out.println("ip:"+p.getProperty("ip")+",port:"+p.getProperty("port"));  

3.读取xml文件

1).利用ClassPathXmlApplicationContext

ApplicationContext context = new ClassPathXmlApplicationContext("beanConfig.xml");   
HelloBean helloBean = (HelloBean)context.getBean("helloBean");   
System.out.println(helloBean.getHelloWorld());  

2).利用FileSystemResource读取

Resource rs = new FileSystemResource("D:/software/beanConfig.xml");   
  BeanFactory factory = new XmlBeanFactory(rs);   
  HelloBean helloBean = (HelloBean)factory.getBean("helloBean");\   
  System.out.println(helloBean.getHelloWorld());   

相关文章

网友评论

      本文标题:java读取Resources下文件及任意位置文件

      本文链接:https://www.haomeiwen.com/subject/cknymctx.html