扫描二维码下载沐宇APP

沐宇

微信扫码使用沐宇小程序

沐宇

java鎬庝箞鑾峰彇閰嶇疆鏂囦欢鍙傛暟

扬州沐宇科技
2023-09-28 17:28:34
Java

鍦↗ava涓紝鍙互浣跨敤java.util.Properties绫绘潵璇诲彇閰嶇疆鏂囦欢涓殑鍙傛暟銆備互涓嬫槸涓€涓畝鍗曠殑绀轰緥锛?/p>

棣栧厛锛屽垱寤轰竴涓悕涓?code>config.properties鐨勯厤缃枃浠讹紝骞跺湪鏂囦欢涓坊鍔犱互涓嬪唴瀹癸細

name=John Doe
age=30

鐒跺悗锛屽湪Java浠g爜涓娇鐢?code>Properties绫昏鍙栭厤缃枃浠朵腑鐨勫弬鏁帮細

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
public class ConfigReader {
public static void main(String[] args) {
Properties properties = new Properties();
FileInputStream configFile = null;
try {
configFile = new FileInputStream("config.properties");
properties.load(configFile);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (configFile != null) {
try {
configFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
String name = properties.getProperty("name");
int age = Integer.parseInt(properties.getProperty("age"));
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}

杩愯涓婅堪浠g爜锛屽皢杈撳嚭浠ヤ笅缁撴灉锛?/p>

Name: John Doe
Age: 30

涓婅堪浠g爜涓紝棣栧厛鍒涘缓浜嗕竴涓?code>Properties瀵硅薄properties锛岀劧鍚庝娇鐢?code>FileInputStream鏉ヨ鍙栭厤缃枃浠?code>config.properties銆傛帴鐫€锛屼娇鐢?code>properties.load(configFile)鏂规硶鍔犺浇閰嶇疆鏂囦欢涓殑鍙傛暟銆傛渶鍚庯紝浣跨敤getProperty鏂规硶鏍规嵁鍙傛暟鍚嶈幏鍙栫浉搴旂殑鍊笺€備娇鐢?code>Integer.parseInt灏嗗瓧绗︿覆绫诲瀷鐨勫勾榫勮浆鎹负鏁存暟绫诲瀷銆?/p>

娉ㄦ剰锛氬湪浣跨敤FileInputStream璇诲彇閰嶇疆鏂囦欢鏃讹紝闇€瑕佹彁渚涢厤缃枃浠剁殑璺緞銆備笂杩扮ず渚嬪亣璁鹃厤缃枃浠朵笌Java浠g爜浣嶄簬鍚屼竴鐩綍涓嬶紝濡傛灉涓嶆槸锛岃鎻愪緵姝g‘鐨勮矾寰勩€?/p>

扫码添加客服微信