import java.io.BufferedReader;
import java.io.CharArrayWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class NameUtils {
public static void main(String[] args) throws IOException {
System.out.println("请输入项目名称");
@SuppressWarnings("resource")
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
System.out.println("你输入是:" + str);
String projectName = str;
String oldName = "city";
if (str.contains(":")) {
projectName = str.split(":")[0];
oldName = str.split(":")[1];
}
System.out.println("替换" + oldName + "为" + projectName);
String projectDir = System.getProperty("user.dir");
System.out.println("项目路径:" + projectDir);
File dir = new File(projectDir);
for (File file : dir.listFiles()) {
String name = file.getName();
if (name.contains(oldName)) {
System.out.println("开始重命名"+name);
name = name.replace(oldName, projectName);
String fileName = projectDir+File.separator+ name;
boolean flag = file.renameTo(new File(fileName));
System.out.println(fileName + "重命名结果"+flag);
} else if (name.equals("settings.txt")) {
System.out.println("开始替换文件内容:"+name);
replacTextContent(file.getAbsolutePath(), oldName, projectName);
System.out.println("替换文件内容结束:"+name);
}
}
System.out.println("开始重命名文件夹:"+dir.getAbsolutePath());
String target = dir.getParent() + File.separator + projectName;
boolean flag = dir.renameTo(new File(target));
System.out.println(target + "重命名文件夹结束:"+ flag);
}
/**
* 替换文本文件中的字符串
*
* @param path
* @throws IOException
*/
public static void replacTextContent(String path, String srcStr, String replaceStr) throws IOException {
// 读
File file = new File(path);
FileReader in = new FileReader(file);
BufferedReader bufIn = new BufferedReader(in);
// 内存流, 作为临时流
CharArrayWriter tempStream = new CharArrayWriter();
// 替换
String line = null;
while ((line = bufIn.readLine()) != null) {
// 替换每行中, 符合条件的字符串
line = line.replaceAll(srcStr, replaceStr);
// 将该行写入内存
tempStream.write(line);
// 添加换行符
tempStream.append(System.getProperty("line.separator"));
}
// 关闭 输入流
bufIn.close();
// 将内存中的流 写入 文件
FileWriter out = new FileWriter(file);
tempStream.writeTo(out);
out.close();
}
}