properties属性文件:
username=admin
password=123456
package Map;
import org.junit.Test;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
/*
一、java.util.Map 接口:用于操作成对对象的集合。具有key(键)-value(值)对映射关系的集合;一个key对应着一个value,key不允许重复
/-------HashMap:是Map接口的典型实现类
/-------LinkedHashMap:与hashset相似
/-------HashTable: 是一个古老的实现,相较于HashMap是线程安全的因此效率低,不建议使用
/-------Properties:用于操作属性文件(properties对应的key和value都是String形式)
/-------TreeMap:
*/
public class PropertiesTest {
@Test
public void test1() throws IOException {
//1、创建Peoperties的实例
Properties props=new Properties();
//2、通过load()加载指定的属性文件
props.load(new FileInputStream("hello.properties"));
//3、通过getProperty()根据key获取对应的value
String username = props.getProperty("username");
String password = props.getProperty("password");
System.out.println(username);
System.out.println(password);
}
}
注意:属性文件在当前包或者项目路径下
TreeMap:
package Map;
import org.junit.Test;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;
/*
一、java.util.Map 接口:用于操作成对对象的集合。具有key(键)-value(值)对映射关系的集合;一个key对应着一个value,key不允许重复
/-------HashMap:是Map接口的典型实现类
/-------LinkedHashMap:与hashset相似
/-------HashTable: 是一个古老的实现,相较于HashMap是线程安全的因此效率低,不建议使用
/-------Properties:用于操作属性文件(properties对应的key和value都是String形式)
/-------TreeMap:根据key拥有指定的排序方式
/--------自然排序(Comparable)
/--------定制排序(Comparator)
*/
public class PropertiesTest {
@Test
public void test3(){
Comparator com=new Comparator() {
@Override
public int compare(Object o1, Object o2) {
if (o1 instanceof Person&&o2 instanceof Person){
Person p1=(Person) o1;
Person p2=(Person) o2;
if (p1.getAge().equals(p2.getAge())){
return p1.getName().compareTo(p2.getName());
}else {
return p1.getAge().compareTo(p2.getAge());
}
}
return 0;
}
};
TreeMap tm=new TreeMap(com);
tm.put(new Person("张三",17),11);
tm.put(new Person("李四",48),22);
tm.put(new Person("王五",55),33);
Set entrySet =tm.entrySet();
Iterator iterator = entrySet.iterator();
while (iterator.hasNext()){
Map.Entry entry = (Map.Entry)iterator.next();
Object key = entry.getKey();
Object value = entry.getValue();
System.out.println(key+"="+value);
}
}
@Test
public void test1() throws IOException {
//1、创建Peoperties的实例
Properties props=new Properties();
//2、通过load()加载指定的属性文件
props.load(new FileInputStream("hello.properties"));
//3、通过getProperty()根据key获取对应的value
String username = props.getProperty("username");
String password = props.getProperty("password");
System.out.println(username);
System.out.println(password);
}
public static void main(String[] args) throws IOException {
//1、创建Peoperties的实例
Properties props=new Properties();
//2、通过load()加载指定的属性文件
props.load(new FileInputStream("./hello.properties"));
//3、通过getProperty()根据key获取对应的value
String username = props.getProperty("username");
String password = props.getProperty("password");
System.out.println(username);
System.out.println(password);
}
}