久久精品人人爽,华人av在线,亚洲性视频网站,欧美专区一二三

java中properties配置文件如何使用

242次閱讀
沒有評論

共計 1074 個字符,預計需要花費 3 分鐘才能閱讀完成。

在 Java 中,可以使用 Properties 類來讀取和寫入配置文件,配置文件通常是以.properties 文件格式保存的。

  1. 讀取配置文件:

首先,創建一個 Properties 對象,并使用其 load() 方法加載配置文件。load() 方法接受一個 InputStream 對象作為參數,可以使用 FileInputStream 或者 ClassLoader 來獲取配置文件的輸入流。例如:

Properties prop = new Properties();
try (InputStream input = new FileInputStream("config.properties")) {prop.load(input);
} catch (IOException ex) {ex.printStackTrace();
}

在加載完成后,可以使用 getProperty() 方法來獲取配置文件中的屬性值。例如:

String url = prop.getProperty("url");
String username = prop.getProperty("username");
String password = prop.getProperty("password");
  1. 寫入配置文件:

首先,創建一個 Properties 對象,并使用其 setProperty() 方法來設置屬性值。例如:

Properties prop = new Properties();
prop.setProperty("url", "jdbc:mysql://localhost:3306/mydb");
prop.setProperty("username", "root");
prop.setProperty("password", "password");

然后,創建一個 OutputStream 對象,并使用 Properties 的 store() 方法將屬性值寫入配置文件。store() 方法接受一個 OutputStream 對象和一個注釋作為參數。例如:

try (OutputStream output = new FileOutputStream("config.properties")) {prop.store(output, "This is a sample config file");
} catch (IOException ex) {ex.printStackTrace();
}

注意:在寫入配置文件時,如果指定的配置文件不存在,store() 方法會自動創建一個新的配置文件。如果配置文件已存在,store() 方法會將原有的配置項替換為新的配置項。

丸趣 TV 網 – 提供最優質的資源集合!

正文完
 
丸趣
版權聲明:本站原創文章,由 丸趣 2023-12-16發表,共計1074字。
轉載說明:除特殊說明外本站除技術相關以外文章皆由網絡搜集發布,轉載請注明出處。
評論(沒有評論)
主站蜘蛛池模板: 汝城县| 张北县| 沂南县| 庐江县| 云阳县| 财经| 卢湾区| 宁武县| 泾川县| 黔江区| 新郑市| 新竹县| 屏南县| 尼木县| 六安市| 昌乐县| 汝城县| 贵定县| 乌拉特中旗| 荆州市| 肥乡县| 无为县| 习水县| 西宁市| 天镇县| 葫芦岛市| 德保县| 特克斯县| 和硕县| 南投市| 万盛区| 栾川县| 武邑县| 乌审旗| 延川县| 德安县| 加查县| 滁州市| 鄯善县| 金华市| 克拉玛依市|