java读取存在src目录下和存在同级目录下的配置文件

深碍√TFBOYSˉ_ 2022-05-23 11:21 388阅读 0赞

如果我有个文件存在src下一级的地方和存在src同级的目录应该怎么用相对路径去获取如图:

set.properties 配置文件里的内容如:20180607184643312" class="reference-link">20180607183652349 set.properties 配置文件里的内容如:20180607184643312

一、如果存在src同级的地方应该是InputStream in = new BufferedInputStream(new FileInputStream(“./set.properties”));就可以了。

代码如下:

  1. import java.io.BufferedInputStream;
  2. import java.io.FileInputStream;
  3. import java.io.InputStream;
  4. import java.util.Iterator;
  5. import java.util.Properties;
  6. public class PropertiesUtil {
  7. public static String getUrlValue(String urlName) {
  8. String url = null;
  9. Properties prop = new Properties();
  10. try {
  11. //ConfigUtil.class.getClassLoader().getSystemClassLoader().getResource(""));
  12. ClassLoader classLoader = PropertiesUtil.class.getClassLoader();// 读取属性文件xxxxx.properties
  13. //InputStream in = classLoader.getResourceAsStream("config/config.properties");
  14. InputStream in = new BufferedInputStream(new FileInputStream("./set.properties"));
  15. prop.load(in); /// 加载属性列表
  16. Iterator<String> it = prop.stringPropertyNames().iterator();
  17. while (it.hasNext()) {
  18. if (it.next().equals(urlName)) {
  19. url = prop.getProperty(urlName);
  20. }
  21. }
  22. in.close();
  23. } catch (Exception e) {
  24. }
  25. return url;
  26. }
  27. public static void main(String []args){
  28. String urlValue = PropertiesUtil.getUrlValue("defaultFileDirectory");
  29. System.out.println("urlValue=="+urlValue);
  30. }
  31. }

二 、如果存在src下一级的地方应该是ClassLoader classLoader = PropertiesUtil.class.getClassLoader();// 读取属性文件xxxxx.properties //InputStream in = classLoader.getResourceAsStream(“set.properties”);就可以了。

代码如下:

  1. import java.io.InputStream;
  2. import java.util.Iterator;
  3. import java.util.Properties;
  4. public class PropertiesUtil {
  5. public static String getUrlValue(String urlName) {
  6. String url = null;
  7. Properties prop = new Properties();
  8. try {
  9. ClassLoader classLoader = PropertiesUtil.class.getClassLoader();// 读取属性文件xxxxx.properties
  10. InputStream in = classLoader.getResourceAsStream("config/config.properties");
  11. //InputStream in = new BufferedInputStream(new FileInputStream("set.properties"));
  12. prop.load(in); /// 加载属性列表
  13. Iterator<String> it = prop.stringPropertyNames().iterator();
  14. while (it.hasNext()) {
  15. if (it.next().equals(urlName)) {
  16. url = prop.getProperty(urlName);
  17. }
  18. }
  19. in.close();
  20. } catch (Exception e) {
  21. }
  22. return url;
  23. }
  24. public static void main(String []args){
  25. String urlValue = PropertiesUtil.getUrlValue("defaultFileDirectory");
  26. System.out.println("urlValue=="+urlValue);
  27. }
  28. }

发表评论

表情:
评论列表 (有 0 条评论,388人围观)

还没有评论,来说两句吧...

相关阅读