新闻资讯

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻资讯列表

java如何读取外部配置文件,java怎么读取一个文件

发布时间:2023-10-16 17:26:35

java如何读取外部配置文件

在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();
try {
FileInputStream fileInputStream = new FileInputStream("config.properties");
properties.load(fileInputStream);
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
String url = properties.getProperty("url");
String username = properties.getProperty("username");
String password = properties.getProperty("password");
System.out.println("URL: " + url);
System.out.println("Username: " + username);
System.out.println("Password: " + password);
}
}

在上面的代码中,首先创建一个Properties对象,然后使用FileInputStream读取配置文件,并使用load方法将文件中的属性加载到Properties对象中。然后,可使用getProperty方法获得指定的属性值。最后,将属性值打印到控制台。
需要注意的是,上述代码中的配置文件名为config.properties,它应当与Java代码在同一目录下。如果配置文件在其他位置,需要指定正确的文件路径。