properties文件的方式
时间: 2024-05-11 18:18:20 浏览: 6
properties文件是一种文本文件,用于存储键值对。在Java中,我们可以使用java.util.Properties类来读取和写入properties文件。
下面是一个示例properties文件:
```
# This is a sample properties file
database.url=jdbc:mysql://localhost:3306/mydb
database.username=myuser
database.password=mypassword
```
在Java中,我们可以使用以下代码读取该文件:
```java
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
public class ReadPropertiesFile {
public static void main(String[] args) throws IOException {
// Create a Properties object
Properties props = new Properties();
// Load the properties file
FileInputStream fis = new FileInputStream("config.properties");
props.load(fis);
fis.close();
// Get the property values
String url = props.getProperty("database.url");
String username = props.getProperty("database.username");
String password = props.getProperty("database.password");
// Print the values
System.out.println("Database URL: " + url);
System.out.println("Username: " + username);
System.out.println("Password: " + password);
}
}
```
该代码将打印以下输出:
```
Database URL: jdbc:mysql://localhost:3306/mydb
Username: myuser
Password: mypassword
```
我们还可以使用以下代码将属性写入properties文件:
```java
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
public class WritePropertiesFile {
public static void main(String[] args) throws IOException {
// Create a Properties object
Properties props = new Properties();
// Set the properties values
props.setProperty("database.url", "jdbc:mysql://localhost:3306/mydb");
props.setProperty("database.username", "myuser");
props.setProperty("database.password", "mypassword");
// Save the properties to the file
FileOutputStream fos = new FileOutputStream("config.properties");
props.store(fos, "Database configuration");
fos.close();
}
}
```
该代码将创建一个名为config.properties的文件,并将以下内容写入该文件:
```
# Database configuration
database.url=jdbc:mysql://localhost:3306/mydb
database.username=myuser
database.password=mypassword
```
这就是使用properties文件的基本方法。