admin
2021-11-13 5ac194b4319c4f1e1e0e167243ffcc20d8924961
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package com.ks.codegenerator.utils;
 
import org.springframework.util.FileCopyUtils;
 
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
 
/**
 * @author hxh
 * @title: FileUtils
 * @description: TODO
 * @date 2021/11/13 15:55
 */
public class FileUtils {
 
 
    /**
     * @return void
     * @author hxh
     * @description 复制文件夹
     * @date 15:56 2021/11/13
     * @param: sourceDir
     * @param: destDir
     **/
    public static void copyFileDir(String sourceDir, String destDir) throws IOException {
 
        if (!new File(destDir).exists()) {
            new File(destDir).mkdirs();
        }
 
        File[] fs = new File(sourceDir).listFiles();
        if (fs != null) {
            for (File f : fs) {
                if (f.isFile()) {
                    String destFile = destDir + "/" + f.getName();
                    FileCopyUtils.copy(f, new File(destFile));
                } else {
                    copyFileDir(f.getPath(), destDir + "/" + f.getName());
                }
            }
        } else {
            //空文件夹
            new File(destDir).mkdir();
        }
 
    }
 
 
    /**
     * @return void
     * @author hxh
     * @description 替换文件中的内容
     * @date 15:57 2021/11/13
     * @param: file
     * @param: from
     * @param: to
     **/
    public static void replaceFileContent(String file, String from, String to) throws Exception {
        if (!new File(file).exists()) {
            throw new Exception("文件不存在");
        }
 
        // 创建文件输入流
        FileReader fis = new FileReader(file);
        // 创建缓冲字符数组
        char[] data = new char[1024];
        int rn = 0;
        // 创建字符串构建器
        StringBuilder sb = new StringBuilder();
        // fis.read(data):将字符读入数组。在某个输入可用、发生 I/O
        // 错误或者已到达流的末尾前,此方法一直阻塞。读取的字符数,如果已到达流的末尾,则返回 -1
        // 读取文件内容到字符串构建器
        while ((rn = fis.read(data)) > 0) {
            // 把数组转换成字符串
            String str = String.valueOf(data, 0, rn);
            sb.append(str);
        }
        fis.close();// 关闭输入流
        // 从构建器中生成字符串,并替换搜索文本
        String str = sb.toString().replace(from, to);
        // 创建文件输出流
        FileWriter fout = new FileWriter(file);
        // 把替换完成的字符串写入文件内
        fout.write(str.toCharArray());
        fout.close();// 关闭输出流
    }
 
    public static void renameFile(String file, String name) throws Exception {
        if (!new File(file).exists()) {
            throw new Exception("文件不存在");
        }
        new File(file).renameTo(new File(new File(file).getParent(), name));
    }
 
 
}