共計(jì) 888 個(gè)字符,預(yù)計(jì)需要花費(fèi) 3 分鐘才能閱讀完成。
在 Java 中,可以使用 Properties
類(lèi)來(lái)讀取外部配置文件。下面是一個(gè)示例代碼,展示了如何讀取外部配置文件:
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);
}
}
在上面的代碼中,首先創(chuàng)建一個(gè) Properties
對(duì)象,然后使用 FileInputStream
讀取配置文件,并使用 load
方法將文件中的屬性加載到 Properties
對(duì)象中。然后,可以使用 getProperty
方法獲取指定的屬性值。最后,將屬性值打印到控制臺(tái)。
需要注意的是,上述代碼中的配置文件名為config.properties
,它應(yīng)該與 Java 代碼在同一目錄下。如果配置文件在其他位置,需要指定正確的文件路徑。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完