為了配置目的,使用配置文件是一個好的重用方式。在這種情況下,當代碼打包到一個jar文件中時,其他用戶可以將不同的配置放在config.properties文件中。以下是使用屬性文件的簡單示例。
1.按照如下創建文件層次結構。主要把config.properties文件放在src包中。其他測試代碼和數據庫類放在src下的不同包中。
配置文件位置
代碼示例
package Test;
import java.io.IOException;
import java.util.Properties;
public class Test {
public static void main(String[] args) {
Properties configFile = new Properties();
try {
configFile.load(Test.class.getClassLoader().getResourceAsStream("config.properties"));
String name = configFile.getProperty("name");
System.out.println(name);
} catch (IOException e) {
e.printStackTrace();
}
}
}
3. 輸出內容
"key=value".