IO和Properties的联合使用
IO流:文件的读和写
Properties:是一个Map集合,key和value都是String类型
1 package IoTest; 2 3 import java.io.FileNotFoundException; 4 import java.io.FileReader; 5 import java.io.IOException; 6 import java.util.Properties; 7 8 public class IOandPropertiesTest { 9 10 public static void main(String[] args) throws Exception{ 11 /* 12 * Properties是一个Map集合,key和value都是String类型。 13 * 想将userinfo文件中的数据加载到Properties对象当中 14 * 15 * 以后经常改变的数据可以单独写到一个文件中,使用程序动态读取。将来只需要修改这个文件的内容,java代码不需要做改动,不需要重新编译, 16 * 服务器也不需要重启,就可以获得动态信息 17 * 18 * 类似于以上机制的这种文件可以被称为配置文件,并且当配置文件的内容格式是: 19 * key1=value; 20 * key2=value; 21 * 的时候,将这种配置文件称为属性配置文件。 22 * 23 * java规范中有要求:属性配置文件建议以properties结尾,但这不是必须的。以.properties结尾的文件在java中被称为属性配置文件, 24 * 其中Properties是专门存放属性配置文件内容的一个类 25 */ 26 27 //新建输入流对象 28 FileReader reader=new FileReader("userinfo"); 29 30 //新建一个Map集合 31 Properties pro=new Properties(); 32 33 //调用Properties对象的Load方法将文件中的数据加载到Map集合中 34 pro.load(reader); //文件中的数据顺着管道加载到Map集合中,其中"="左边做key,右边做value 35 36 //通过key来获取value 37 String username=pro.getProperty("username"); 38 String password=pro.getProperty("password"); 39 System.out.println(username); 40 System.out.println(password); 41 } 42 43 44 45 }

浙公网安备 33010602011771号