java从文件中读取信息保存到Map中,修改Map中的值,将Map更新到文件中

方法:map导出到file,从file中读取得到map

package com.filetomap;

import java.io.BufferedReader; 
import java.io.File; 
import java.io.FileReader; 
import java.io.FileWriter; 
import java.io.IOException; 
import java.util.HashMap; 
import java.util.Map;

/** 
* 创建一个file,后缀名为cfg. 里面文本格式为每行:A=X结构,其中注释在最前面加上# 然后将该文件保存到map中(map(A,X); 
* 
* @author Administrator 
* 
*/ 
public class FileToMap1 { 
    private String line = System.getProperty(“line.separator”); 
    private String separ = “=”;
    static String basePath = System.getProperty(“user.dir”); 
    static String filePath = “./Alms.cfg”;// 文件相对路径
    public static void main(String[] args) {
    FileToMap1 fileToMap1 = new FileToMap1();
    Map<String, String> oldMap = fileToMap1.fTM();
    Map<String, String> newMap = new HashMap<String, String>();
    newMap.put("A", "A''");
    Map<String, String> map = fileToMap1.newMapToOldMap(newMap, oldMap, false);
    try {
        fileToMap1.mapToFileDefault(map, new File(filePath), fileToMap1.separ);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

/**
 * 有参构造函数
 * 
 * @param separ
 * @param filePath
 */
public FileToMap1(String separ, String filePath) {
    this.filePath = filePath;
    this.separ = separ;
    File file = new File(filePath);
    if (!file.exists()) {
        System.out.println("文件不存在");
        try {
            file.createNewFile();
        } catch (IOException e) {
            System.out.println("路径:" + filePath + "创建失败");
            e.printStackTrace();
        }
    }
}

/**
 * 无参构造函数,用类默认的配置。
 */
public FileToMap1() {
    File file = new File(filePath);
    if (!file.exists()) {
        System.out.println("文件不存在");
        try {
            file.createNewFile();
        } catch (IOException e) {
            System.out.println("路径:" + filePath + "创建失败");
            e.printStackTrace();
        }
    }
}

/**
 * 将map写入到file文件中。默认map(String A,String A')file中以A=A'来表示,map中每个键值对显示一行
 * @throws IOException 
 */
private File mapToFileDefault(Map<String, String> map,File file,String separ) throws IOException{
    StringBuffer buffer = new StringBuffer();
    FileWriter writer = new FileWriter(file, false);
    for(Map.Entry entry:map.entrySet()){
        String key = (String) entry.getKey();
        String value = (String) entry.getValue();
        buffer.append(key + "=" + value).append(line);
    }
    writer.write(buffer.toString());
    writer.close();
    return file;

}
/**
 * 在newMap替换oldMap时,是否覆盖(isOverwrite)如果是,就直接替换,如果否,则将oldMap中的key前加“#”,默认为否
 * @param newMap
 * @param oldMap
 * @return
 */
private Map<String, String> newMapToOldMapDefault(Map<String, String> newMap,Map<String, String> oldMap){
    return newMapToOldMap(newMap,oldMap,false);
}

/**
 * 在newMap替换oldMap时,是否覆盖(isOverwrite)如果是,就直接替换,如果否,则将oldMap中的key前加“#”,默认为否
 */
private Map<String, String> newMapToOldMap(Map<String, String> newMap,
        Map<String, String> oldMap, boolean isOverwrite) {
    // 由于oldMap中包含了file中更多内容,所以newMap中内容在oldMap中调整后,最后返回oldMap修改之后的map.
    // 如果选择true覆盖相同的key
    if (isOverwrite) {
        // 循环遍历newMap
        for (Map.Entry entry : newMap.entrySet()) {
            String newKey = (String) entry.getKey();
            String newValue = (String) entry.getValue();
            oldMap.put(newKey, newValue);
        }
    } else {
        // 不覆盖oldMap,需要在key相同的oldMap的key前加#;
        // 循环遍历newMap
        for (Map.Entry entry : newMap.entrySet()) {
            String newKey = (String) entry.getKey();
            String newValue = (String) entry.getValue();
            String oldValue = oldMap.get(newKey);
            oldMap.put("#" + newKey, oldValue);
            oldMap.put(newKey, newValue);
        }
    }
    return oldMap;
}

/**
 * 将文件转换成map存储
 * 
 * @return
 */
private Map<String, String> fTM() {
    Map<String, String> map = new HashMap<String, String>();
    File file = new File(filePath);
    BufferedReader reader = null;
    try {
        System.out.println("以行为单位读取文件内容,一次读一整行:");
        reader = new BufferedReader(new FileReader(file));
        String tempString = null;
        int line = 1;
        // 一次读入一行,直到读入null为文件结束
        while ((tempString = reader.readLine()) != null) {
            // 显示行号
            System.out.println("line " + line + ": " + tempString);
            if (!tempString.startsWith("#")) {
                String[] strArray = tempString.split("=");
                map.put(strArray[0], strArray[1]);
            }
            line++;
        }
        reader.close();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e1) {
            }
        }
    }
    for (Map.Entry entry : map.entrySet()) {
        System.out.println(entry.getKey() + "=" + entry.getValue());
    }
    return map;
}

转载自:https://blog.csdn.net/zp357252539/article/details/47403179

可以使用Java的IO流和Map集合来实现将文件的字符读取Map集合计算出现的字符。具体步骤如下: 1. 创建一个File对象,指定要读取文件路径。 2. 创建一个FileReader对象,用于读取文件的字符。 3. 创建一个HashMap<Character, Integer>对象,用于存储每个字符出现的次数。 4. 使用while循环读取文件的每一个字符,并将其存储Map集合。 5. 如果字符在Map集合不存在,则将该字符作为键,出现次数初始化为1作为存储Map集合。 6. 如果字符在Map集合已经存在,则将该字符对应的加1。 7. 最后遍历Map集合,输出每个字符出现的次数。 代码如下: ```java import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.util.HashMap; import java.util.Map; public class CountCharacters { public static void main(String[] args) throws Exception { File file = new File("test.txt"); // 创建File对象 FileReader reader = new FileReader(file); // 创建FileReader对象 Map<Character, Integer> map = new HashMap<>(); // 创建HashMap对象 int ch; while ((ch = reader.read()) != -1) { // 读取文件的每一个字符 char c = (char) ch; if (map.containsKey(c)) { // 如果字符在Map集合已经存在 int count = map.get(c); map.put(c, count + 1); // 将该字符对应的加1 } else { // 如果字符在Map集合不存在 map.put(c, 1); // 将该字符作为键,出现次数初始化为1作为存储Map集合 } } reader.close(); // 关闭读取器 for (Map.Entry<Character, Integer> entry : map.entrySet()) { // 遍历Map集合 System.out.println(entry.getKey() + "出现了" + entry.getValue() + "次"); // 输出每个字符出现的次数 } } } ``` 注意:上述代码只能统计ASCII码表的字符出现次数,如果要统计Unicode字符出现次数,需要使用Unicode编码。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值