共計 853 個字符,預計需要花費 3 分鐘才能閱讀完成。
在 Java 中,可以使用 java.util.Properties
類來讀取配置文件。以下是一個簡單的例子:
- 創(chuàng)建一個名為
config.properties
的配置文件,內(nèi)容如下:
username=admin
password=123456
- 在 Java 代碼中使用
Properties
類來讀取配置文件:
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
public class ConfigReader {public static void main(String[] args) {Properties prop = new Properties();
FileInputStream input = null;
try {input = new FileInputStream("config.properties");
prop.load(input);
String username = prop.getProperty("username");
String password = prop.getProperty("password");
System.out.println("username:" + username);
System.out.println("password:" + password);
} catch (IOException ex) {ex.printStackTrace();
} finally {if (input != null) {
try {input.close();
} catch (IOException e) {e.printStackTrace();
}
}
}
}
}
運行以上代碼,將會輸出:
username: admin
password: 123456
以上代碼使用 Properties
類的 getProperty
方法來獲取配置文件中的屬性值。配置文件需要位于 Java 代碼所在的目錄中,或者通過相對路徑或絕對路徑指定其位置。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完