在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代码在同一目录下。如果配置文件在其他位置,需要指定正确的文件路径。

