共計 1066 個字符,預計需要花費 3 分鐘才能閱讀完成。
在 Java 中,可以使用 java.util.Properties
類來讀取配置文件中的參數。以下是一個簡單的示例:
首先,創建一個名為 config.properties
的配置文件,并在文件中添加以下內容:
name=John Doe
age=30
然后,在 Java 代碼中使用 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);
}
}
運行上述代碼,將輸出以下結果:
Name: John Doe
Age: 30
上述代碼中,首先創建了一個 Properties
對象 properties
,然后使用FileInputStream
來讀取配置文件 config.properties
。接著,使用properties.load(configFile)
方法加載配置文件中的參數。最后,使用 getProperty
方法根據參數名獲取相應的值。使用 Integer.parseInt
將字符串類型的年齡轉換為整數類型。
注意:在使用 FileInputStream
讀取配置文件時,需要提供配置文件的路徑。上述示例假設配置文件與 Java 代碼位于同一目錄下,如果不是,請提供正確的路徑。
丸趣 TV 網 – 提供最優質的資源集合!
正文完