1. 程式人生 > 實用技巧 >Java對本地檔案內容讀取、修改、刪除的操作

Java對本地檔案內容讀取、修改、刪除的操作

import org.apache.commons.lang.StringUtils;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * 檔案的讀,寫,刪除操作
 */
public class FileUtil {

    /**
     * 讀取檔案,用於檔案回顯到頁面
     * @param url   檔案路徑 + 檔名
     * @return  string 屬性
     */
    public static String readFile(String url) {
        BufferedReader br = null;
        String file = "";
        try {
            br = new BufferedReader(new FileReader(url));    // 讀取檔案

            String line = null;
            while((line = br.readLine()) != null) {    // 按行讀取
                if(StringUtils.isNotBlank(line)) {
                    file += line +";";
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return file;
    }


    /**
     * 刪除檔案
     * @param url       檔案路徑 + 檔名
     * @param content   刪除的內容用 ; 隔開
     */
    public static void removeFile(String url, String content) {
        String s = readFile(url);   // 讀取檔案

        String[] split = content.split(";");    // 刪除的內容
        Map<String, String> map = new HashMap<>();
        for(String sp: split) {
            String[] split1 = sp.split("=");
            map.put(split1[0], split1[1]);
        }

        String[] string = s.split(";");     // 原檔案內容
        String write = "";  // 寫入檔案的新陣列
        for(String str: string) {
            if(str.contains("#")) { // 過濾註釋
                write += str +";";
            }else {
                String[] split1 = str.split("=");
                String s1 = map.get(split1[0]);

                String untrue = map.get("untrue");  // 屬性值[mysqld] || [client]

                if(StringUtils.isNotBlank(untrue)) {
                    if(untrue.equals(split1[split1.length - 1])) {
                        map.keySet().removeIf(key -> key.startsWith("untrue"));   // 刪除已經賦值元素
                    }else {
                        if(StringUtils.isBlank(s1)) {    // map沒有這個屬性,不刪除
                            write += str +";";
                        }else {
                            map.keySet().removeIf(key -> key.startsWith(split1[0]));   // 刪除已經賦值元素
                        }
                    }

                }else {
                    if(StringUtils.isBlank(s1)) {    // map沒有這個屬性,不刪除
                        write += str +";";
                    }else {
                        map.keySet().removeIf(key -> key.startsWith(split1[0]));   // 刪除已經賦值元素
                    }
                }
            }
        }

        String property = System.getProperty("line.separator"); // 針對於不同性質的作業系統的換行

        BufferedWriter o = null;  // 寫入刪除後內容
        try {
            o = new BufferedWriter(new FileWriter(url));
            String[] split1 = write.split(";");

            for(String spl: split1) { // 更新檔案
                o.write(spl + property);
            }

        } catch (IOException e) {
            e.printStackTrace();

        } finally {
            if(o != null) {
                try {
                    o.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    /**
     * 更新檔案
     * @param url   檔案路徑,用 / 結尾
     * @param file  檔名
     * @param content   修改追加的檔案內容,或者修改的檔案內容,用 ; 分割
     */
    public static void updateFile(String url, String file, String content) {

        BufferedReader br = null;
        BufferedWriter out = null;
        BufferedWriter o = null;

        String property = System.getProperty("line.separator"); // 針對於不同性質的作業系統的換行

        try {
            br = new BufferedReader(new FileReader(url + file));    // 讀取檔案

            File f = new File(url +"copy_"+ file);  // 備份檔案
            if(!f.exists()) {
                f.createNewFile(); // 建立檔案
            }

            out = new BufferedWriter(new FileWriter(url +"copy_"+ file));   // 備份檔案寫入

            String[] split = content.split(";");    // 處理需要寫入的新資料
            Map<String, String> map = new HashMap<>();  // 儲存新資料
            for(String s: split) {
                String[] strings = s.split("=");
                map.put(strings[0], strings[1]);
            }

            String line = null;
            String write = "";
            while ((line = br.readLine()) != null) {    // 按行讀取
                if(StringUtils.isNotBlank(line)) {
                    out.write(line + property); // 寫入備份檔案,換行寫入

                    if(line.contains("#")) {    // # 開頭是註釋 [] 是標註,原樣儲存
                        write += line + ";";

                    }else { // 根據輸入的內容,原本存在的屬性,修改;原本沒有的屬性,追加
                        String[] strings = line.split("="); // 前面是屬性,後面是數值,原值
                        String s = map.get(strings[0]); // 根據key獲取新賦值數值
                        String untrue = map.get("untrue");  // 屬性值[mysqld] || [client]

                        if(StringUtils.isNotBlank(untrue)) {
                            if(untrue.equals(strings[strings.length - 1])) {    // 屬性值存在,不操作
                                write += line +";";

                                map.keySet().removeIf(key -> key.startsWith("untrue"));   // 刪除已經賦值元素
                            }else {
                                if(StringUtils.isNotBlank(s)) {     // 更改的屬性
                                    write += strings[0] +"="+ s +";";

                                    map.keySet().removeIf(key -> key.startsWith(strings[0]));   // 刪除已經賦值元素
                                }else { // 新增沒有此屬性,原值儲存
                                    write += line +";";
                                }
                            }
                        }else {
                            if(StringUtils.isNotBlank(s)) {     // 更改的屬性
                                write += strings[0] +"="+ s +";";

                                map.keySet().removeIf(key -> key.startsWith(strings[0]));   // 刪除已經賦值元素
                            }else { // 新增沒有此屬性,原值儲存
                                write += line +";";
                            }
                        }
                    }
                }
            }

            for(Map.Entry<String, String> m : map.entrySet()) {    // 新增的屬性
                if(m.getKey().equals("untrue")) {   // 用於只有一個數值,沒有key的屬性
                    write += m.getValue() +";";
                }else {
                    write += m.getKey() +"="+ m.getValue() +";";
                }
            }

            o = new BufferedWriter(new FileWriter(url + file));  // 原檔案追加或修改屬性

            String[] split1 = write.split(";");
            for(String s: split1) { // 更新檔案
                o.write(s + property);
            }

        } catch (IOException e) {
            e.printStackTrace();

        } finally {
            if(br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if(out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if(o != null) {
                try {
                    o.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}

呼叫方式:

// 讀取檔案內容
@GetMapping("/read")
public void read() {
    String file = FileUtil.readFile("/Users/Desktop/my.cnf");
    String[] split = file.split(";");
    for(String s: split) {
        if(!s.contains("#")) {  // 去掉註釋
            System.out.println("讀取到的檔案:"+ s);
        }
    }
}

// 修改檔案內容
@GetMapping("/update")
public void update() {
    String s = "max_allowed_packet=521M;untrue=[client];";
    FileUtil.updateFile("/Users/Desktop/", "my.cnf", s);
}

// 刪除檔案內容
@GetMapping("/remove")
public void remove() {
    String s = "max_allowed_packet=521M;untrue=[client];";
    FileUtil.removeFile("/Users/Desktop/my.cnf", s);
}

* 不適用於檔案特別大的場景