一、IO和Properties联合使用:
- Properties是一个map集合(key,value),键值都是String类型。
- 本程序用于将文件中的键值对加载到Properties对象中。
- 以后经常改变的数据,可以单独写到一个文件中,使用该程序动态读取。
- 类似于myfile的这种文件被称为配置文件。如果格式内容是key=file的时候,叫属性配置文件,建议以properties结尾。
- 属性配置文件中#是注释,key重复的话value会自动覆盖,=前后不能有空格。
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;
public class Test{
public static void main(String[] args) {
FileReader reader = null;
try {
reader = new FileReader("javase\\src\\myfile");
Properties p = new Properties();
p.load(reader);//load方法将文件中的数据以键值对的方式加载到集合中,文件中存储格式“key=value”
System.out.println(p.getProperty("key1"));
System.out.println(p.getProperty("key2"));
System.out.println(p.getProperty("username"));
System.out.println(p.getProperty("password"));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
二、资源绑定器:
用于获取属性配置文件中的内容。
import java.util.ResourceBundle;
public class Test{
public static void main(String[] args) {
ResourceBundle bundle = ResourceBundle.getBundle("myfile");
String s = bundle.getString("name");
System.out.println(s);
}
}
只能用于.properties文件且文件必须位于类路径(src)下。