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));
|
}
|
|
|
}
|