properties的使用
来源:互联网 发布:ubuntu运行lua文件 编辑:程序博客网 时间:2024/05/17 05:00
在程序中我们可能会遇到想要修改属性的某些初始化值时,一般的做法是修改代码里面的初始值,使用properties可以让我们不修改代码就可以实现修改初始值的功能.
properties的使用方法和HashMap的存储是一样的,都是通过key-value的方法,不同的是,会生成一个.properties的文件保存数据.
public static void main(String[] args) { // Property 属性 继承自Hashtable // Hashtable 和Hashmap是一样的 // 区别在于Hashtable中key和value的值都不能为null,Hashmap可以 Hashtable<String, String> ht = new Hashtable<String,String>(); // ht.put(null, null); NullPointerException HashMap<String, String> ht1 = new HashMap<String,String>(); }
创建一个properties文件
public class Test2 { public static void main(String[] args) { // 属性列表 Properties properties = new Properties(); properties.setProperty("name", "张三"); properties.setProperty("age", "18"); // 通过输出流保存到硬盘上 // 相对路径,保存在工程目录下 try (FileOutputStream fileOutputStream = new FileOutputStream("people.properties");){ properties.store(fileOutputStream, "Save info"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }}
从文件中读取
import java.io.FileInputStream;import java.util.Properties;public class Test3 { public static void main(String[] args) { // 通过key-value 的访问方式 // 可以不通过修改程序获取不同的执行效果 // 使用properties从配置文件中加载属性的值,可以随着文件的变化而变化 Properties properties = new Properties(); try (FileInputStream fileInputStream = new FileInputStream("people.properties");){ // 从指定的流中加载数据 properties.load(fileInputStream); } catch (Exception e) { } // 加载完毕,获取数据 根据key获取value String name = properties.getProperty("name"); String age = properties.getProperty("age"); String school = properties.getProperty("school"); System.out.println(name + age + school); }}
阅读全文
0 0
- 使用JAVA的Properties
- Properties 类的使用
- Properties 类的使用
- log4j.properties的使用
- properties类的使用
- 配置文件properties的使用
- properties文件的使用
- Properties的使用
- 档案文件properties的使用
- Properties的使用
- Properties类的使用
- android Properties的使用
- Properties的使用
- Properties对象的使用
- Properties的使用
- Properties的使用
- Properties类的使用
- Properties的基本使用
- sql基础(一)
- 算法之001RotateArray
- Android Studio中的项目如何上传到GitHub中
- 机器视觉-角点检测算法
- java多线程(一)
- properties的使用
- sbt第一次运行下载jar包很慢解决办法
- 构建Docker私有仓库
- 一个for循环输出九九乘法口诀表
- CSAPP 第三、五、六、七章
- 基本数据的自动类型转换和强制类型转换
- unable to load class for jsp
- 搜索--数独
- C/C++ register关键字学习