关于一些对map和整行读取文件操作
public static void main(String[] args) {
Map<String, String> map = new HashMap<String, String>();
map.put("1", "value1");
map.put("2", "value2");
map.put("3", "value3");
//第一种:普遍使用,二次取值
System.out.println("通过Map.keySet遍历key和value:");
for (String key : map.keySet()) {
System.out.println("key= "+ key + " and value= " + map.get(key));
}
//第二种
System.out.println("通过Map.entrySet使用iterator遍历key和value:");
Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, String> entry = it.next();
System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
}
//第三种:推荐,尤其是容量大时
System.out.println("通过Map.entrySet遍历key和value");
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
}
//第四种
System.out.println("通过Map.values()遍历所有的value,但不能遍历key");
for (String v : map.values()) {
System.out.println("value= " + v);
}
}
//读取文件并且对map排序
- public class Testing {
- public static void main(String[] args) {
- HashMap<String,Double> map = new HashMap<String,Double>();
- ValueComparator bvc = new ValueComparator(map);
- TreeMap<String,Double> sorted_map = new TreeMap<String,Double>(bvc);
- map.put("A",99.5);
- map.put("B",67.4);
- map.put("C",67.4);
- map.put("D",67.3);
- System.out.println("unsorted map: "+map);
- sorted_map.putAll(map);
- System.out.println("results: "+sorted_map);
- }
- }
- class ValueComparator implements Comparator<String> {
- Map<String, Double> base;
- public ValueComparator(Map<String, Double> base) {
- this.base = base;
- }
- // Note: this comparator imposes orderings that are inconsistent with equals.
- public int compare(String a, String b) {
- if (base.get(a) >= base.get(b)) {
- return -1;
- } else {
- return 1;
- } // returning 0 would merge keys
- }
- }
//读取文本文件中数据按行读取
1.读取一个txt文件,方法很多种我使用了字符流来读取(为了方便)
FileReader fr = new FileReader("f:\\TestJava.Java");
BufferedReader bf = new BufferedReader(fr);
//这里进行读取
int b;
while((b=bf.read())!=-1){
System.out.println(bf.readLine());
}
发现每行的第一个字符都没有显示出来,原因呢:b=bf.read())!=-1 每次都会先读取一个字节出来,所以后面的bf.readLine());
读取的就是每行少一个字节
所以,应该使用
String valueString = null;
while ((valueString=bf.readLine())!=null){
System.out.println(valueString);
}