java中properties配置文件如何使用

43次阅读
没有评论

共计 1074 个字符,预计需要花费 3 分钟才能阅读完成。

在 Java 中,可以使用 Properties 类来读取和写入配置文件,配置文件通常是以.properties 文件格式保存的。

  1. 读取配置文件:

首先,创建一个 Properties 对象,并使用其 load() 方法加载配置文件。load() 方法接受一个 InputStream 对象作为参数,可以使用 FileInputStream 或者 ClassLoader 来获取配置文件的输入流。例如:

Properties prop = new Properties();
try (InputStream input = new FileInputStream("config.properties")) {prop.load(input);
} catch (IOException ex) {ex.printStackTrace();
}

在加载完成后,可以使用 getProperty() 方法来获取配置文件中的属性值。例如:

String url = prop.getProperty("url");
String username = prop.getProperty("username");
String password = prop.getProperty("password");
  1. 写入配置文件:

首先,创建一个 Properties 对象,并使用其 setProperty() 方法来设置属性值。例如:

Properties prop = new Properties();
prop.setProperty("url", "jdbc:mysql://localhost:3306/mydb");
prop.setProperty("username", "root");
prop.setProperty("password", "password");

然后,创建一个 OutputStream 对象,并使用 Properties 的 store() 方法将属性值写入配置文件。store() 方法接受一个 OutputStream 对象和一个注释作为参数。例如:

try (OutputStream output = new FileOutputStream("config.properties")) {prop.store(output, "This is a sample config file");
} catch (IOException ex) {ex.printStackTrace();
}

注意:在写入配置文件时,如果指定的配置文件不存在,store() 方法会自动创建一个新的配置文件。如果配置文件已存在,store() 方法会将原有的配置项替换为新的配置项。

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-12-16发表,共计1074字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)