java代码中读取配置文件
时间: 2024-05-12 14:20:14 浏览: 13
在Java代码中,可以使用Java的Properties类来读取配置文件。以下是读取配置文件的示例代码:
```java
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
public class ReadConfigFile {
public static void main(String[] args) {
Properties prop = new Properties();
FileInputStream input = null;
try {
input = new FileInputStream("config.properties");
prop.load(input);
String url = prop.getProperty("url");
String username = prop.getProperty("username");
String password = prop.getProperty("password");
System.out.println("url : " + url);
System.out.println("username : " + username);
System.out.println("password : " + password);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
```
在上面的代码中,我们首先创建了一个Properties对象,然后使用FileInputStream读取配置文件,并将其加载到Properties对象中。最后,我们使用getProperty()方法来获取配置文件中的值,并打印出来。需要注意的是,我们需要在finally块中关闭文件输入流。