1. 目的
记录一下读取文件生成properties,这个经常有用到,以供他人和自己后续参考。
2. 相对路径和绝对路径
先来说一下相对路径和绝对路径的区别,我的认知:
相对路径:不包括盘符(C:),如test.properties
绝对路径:包括盘符(C:),如c:\test\test.properties
最主要的差别是是否包括盘符,后续会通过这一特点做相对或绝对路径判断。
3. 代码
- import部分
其中io.netty这个import不用理会,只是用做写log而已。
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Properties;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
- 程序部分
如下的Java代码,解析一下:
最后的一个function是isAbsolutePath(),这个就是用来判断是相对路径还是绝对路径。
public class ApplicationProperty {
private static final InternalLogger logger = InternalLoggerFactory.getInstance(ApplicationProperty.class);
public static void main(String[] args) {
String path = "application.properties";
System.out.println("绝对路径=" + isAbsolutePath(path));
System.out.println(path);
Properties properties = generateApplicationProperties(path);
System.out.println("port=" + properties.getProperty("ftp.port", "unknow"));
}
/**
* Generate properties by reading file.
* The location of the file can be in the same path as this class, or it can be in an absolute path.
*
* @param path file location
* @return properties
*/
public static Properties generateApplicationProperties(String path) {
Properties props = new Properties();
try {
logger.info("Generate properties from file, " + path);
if (isAbsolutePath(path)) {
logger.info("Generate application properties by using absolute path!");
BufferedReader bufferedReader = new BufferedReader(new FileReader(path));
props.load(bufferedReader);
} else {
logger.info("Generate application properties by using relative path!");
props.load(ApplicationProperty.class.getResourceAsStream(path));
}
} catch (Exception e) {
logger.error(e);
}
return props;
}
public static boolean isAbsolutePath(String path) {
return path.indexOf(":") == 1;
}
}
4. 分析
这个代码的功能就是根据传的相对路径(需要与该类同路径)下的文件或者绝对路径(任意路径)的文件生成properties。