批量讀寫文件並修改

package com.digiccy.publish;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;

import com.digiccy.publish.common.JsonUtil;
import com.digiccy.publish.dao.dto.ZHDto;

public class FileUtils {

    private static void getFiles(File dir) throws IOException {
        if (dir.exists()) {
            if (dir.isDirectory()) {
                System.out.println(dir);
                File[] files = dir.listFiles();
                for (File file : files) {
                    getFiles(file);
                }
            } else {
                System.out.println(dir);
                readJson(dir);
            }
        }
    }

    private static void readJson(File file) throws IOException {
        BufferedReader bReader = new BufferedReader(new FileReader(file));
        String str = null;
        StringBuffer line = new StringBuffer();
        while ((str = bReader.readLine()) != null) {
            line.append(str);
//          line.append("\n");
        }
        String path = file.toString();
        String value = putMsg(line.toString());
        ;
        putMsgToText(value, path);
        bReader.close();
    }

    private static String putMsg(String msg) {
        ZHDto zhDto = new ZHDto();
        String title = null;
        String tags = null;
        String text = null;
        int i = msg.indexOf("Tags: ");
        int x = msg.indexOf("]") + 1;
        int y = msg.indexOf("[");
        int z = msg.length();
        if (i != -1 && x != -1) {
            title = msg.substring(0, i).trim();
            tags = msg.substring(y, x).trim();
            text = msg.substring(x, z).trim();
        }
        zhDto.setTitle(title);
        zhDto.setTags(tags);
        zhDto.setText(text);
        return JsonUtil.toJson(zhDto);
    }

    private static void putMsgToText(String message, String path) {
        System.out.println(message);
        File file = new File(path);// 保證創建一個文件

        if (!file.getParentFile().exists()) {// 如果父目錄不存在,創建父目錄
            file.getParentFile().mkdirs();
        }
        if (file.exists()) {// 如果已經存在,刪除舊文件
            file.delete();
        }
        try (BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, false)))) {
            bw.write(message);
            bw.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        File file = new File("C:/Users/hp/Desktop/textrt_with_tags");
        FileUtils.getFiles(file);
    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章