读取配置文件,先读取config目录,再读取user.dir目录,再读取默认classpath目录。

    1. import java.io.File;
    2. import java.io.FileInputStream;
    3. import java.io.IOException;
    4. import java.io.InputStream;
    5. import java.util.Properties;
    6. public class PropertiesUtil {
    7. public static Properties getProperties(String fileName) {
    8. try {
    9. String outPath = System.getProperty("user.dir") + File.separator + "config" + File.separator + fileName;//先读取config目录的,没有再加载classpath的
    10. if (!new File(outPath).exists()) {
    11. outPath = System.getProperty("user.dir") + File.separator + fileName;
    12. }
    13. Properties properties = new Properties();
    14. InputStream in = new FileInputStream(new File(outPath));
    15. properties.load(in);
    16. return properties;
    17. } catch (IOException e) {
    18. System.out.println(e.getMessage());
    19. try {
    20. Properties properties = new Properties();
    21. InputStream in = PropertiesUtil.class.getClassLoader().getResourceAsStream(fileName);//默认加载classpath的
    22. properties.load(in);
    23. return properties;
    24. } catch (IOException es) {
    25. System.out.println(es.getMessage());
    26. return null;
    27. }
    28. }
    29. }
    30. }