共計(jì) 830 個(gè)字符,預(yù)計(jì)需要花費(fèi) 3 分鐘才能閱讀完成。
在 Java 中,可以使用 java.util.Properties
類來(lái)讀取和使用配置文件。
首先,創(chuàng)建一個(gè) Properties
對(duì)象并加載配置文件??梢允褂?Properties
的load()
方法來(lái)加載配置文件,傳入一個(gè) InputStream
對(duì)象作為參數(shù)。例如,假設(shè)配置文件名為config.properties
,可以使用以下代碼加載該配置文件:
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
public class Main {public static void main(String[] args) {Properties properties = new Properties();
try {properties.load(new FileInputStream("config.properties"));
} catch (IOException e) {e.printStackTrace();
}
// 使用配置文件中的屬性值
String username = properties.getProperty("username");
String password = properties.getProperty("password");
System.out.println("Username:" + username);
System.out.println("Password:" + password);
}
}
然后,可以使用 Properties
對(duì)象的 getProperty()
方法根據(jù)配置文件中的鍵獲取對(duì)應(yīng)的值。
配置文件 config.properties
的內(nèi)容如下:
username=admin
password=123456
運(yùn)行上述代碼,將輸出:
Username: admin
Password: 123456
這樣你就可以在 Java 程序中使用配置文件中的屬性值了。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完