修改项目框架名称工具类

修改项目文件夹名称

import java.io.File;
import java.io.IOException;

/**
 * 修改文件名
 * 感谢 @☜☞E牛仔 提供本文件
 *
 * @Auther: Code
 * @Date: 2018/9/9 18:02
 * @Description: 批量重命名文件
 */
public class ModifyFileName {
    static String OLD_PROJECT_NAME = "gmis";// 要被替换的字符串
    static String NEW_PROJECT_NAME = "gsnm";// 新字符串,如果是去掉前缀后缀就留空,否则写上需要替换的字符串

    //这个路径不能含有zuihou字符!!!!!!! 先将 zuihou-commons-plus 修改为tangyh-commons-plus
    static String dir = "D:\\beifen1\\gsnm-file";// 文件所在路径,所有文件的根目录,记得修改为你电脑上的文件所在路径


    public static void main(String[] args) throws IOException {
        recursiveTraversalFolder(dir);  // 递归遍历此路径下所有文件夹
    }

    /**
     * 递归遍历文件夹获取文件
     */
    public static void recursiveTraversalFolder(String path) {
        File folder = new File(path);
        if (folder.exists()) {
            File[] fileArr = folder.listFiles();
            if (fileArr == null || fileArr.length == 0) {
                System.out.println("文件夹是空的!");
                return;
            } else {
                File newDir = null;// 文件所在文件夹路径+新文件名
                String newName = "";// 新文件名
                String fileName = null;// 旧文件名
                File parentPath = new File("");// 文件所在父级路径
                for (File file : fileArr) {
                    if (file.isDirectory()) {// 是文件夹,继续递归,如果需要重命名文件夹,这里可以做处理
                        fileName = file.getName();
                        if (fileName.contains(OLD_PROJECT_NAME)) {// 文件夹名包含需要被替换的字符串
                            newName = file.getAbsolutePath().replaceAll(OLD_PROJECT_NAME, NEW_PROJECT_NAME);// 新名字
                            File newFile = new File(newName);
                            file.renameTo(newFile);// 重命名

                            System.out.println("文件夹修改前:" + file.getAbsolutePath() + ",修改后" + newName);
                            recursiveTraversalFolder(newFile.getAbsolutePath());
                        }
                        recursiveTraversalFolder(file.getAbsolutePath());
                    } else {// 是文件,判断是否需要重命名
                        fileName = file.getName();
                        parentPath = file.getParentFile();
                        if (fileName.contains(OLD_PROJECT_NAME)) {// 文件名包含需要被替换的字符串
                            newName = fileName.replaceAll(OLD_PROJECT_NAME, NEW_PROJECT_NAME);// 新名字
                            newDir = new File(parentPath + "/" + newName);// 文件所在文件夹路径+新文件名
                            file.renameTo(newDir);// 重命名
                            System.out.println("文件修改前:" + fileName + "修改后:" + newDir);
                        }
                    }
                }
            }
        } else {
            System.out.println("目录不存在=" + path);
        }
    }
}

修改文件夹下文件里面的内容

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.nio.channels.FileChannel;

/**
 * 修改文件中包含 oldStr 的内容,改成newStr
 * <p>
 * 感谢 @☜☞E牛仔 提供本文件
 */
public class ModifyContent {
    //这个路径不能含有zuihou字符!!!!!!! 先将 zuihou-commons-plus 修改为tangyh-commons-plus
    //这个路径不能含有zuihou字符!!!!!!! 先将 zuihou-commons-plus 修改为tangyh-commons-plus
//    static String dir = "/Users/tangyh/gitlab/test/tangyh-commons-plus";// 文件所在路径,所有文件的根目录,记得修改为你电脑上的文件所在路径
    static String dir = "D:\\beifen1\\gsnm-file";// 文件所在路径,所有文件的根目录,记得修改为你电脑上的文件所在路径
    static String newStr = "gsnm";
    static String oldStr = "gmis";

    /**
     * @author itmyhome
     */
    public static void main(String[] args) {
        //这个路径不能含有zuihou字符
        File f = new File(dir);
        print(f, 0, "D:\\beifen1", "D:\\beifen2");
    }

    /**
     * 遍历目录
     *
     * @param f
     * @param len
     */
    public static void print(File f, int len, String sourceDisk, String targetDisk) {
        File[] file = f.listFiles();

        for (int i = 0; i < file.length; i++) {
            if (file[i].isDirectory()) { //推断是否目录
                print(file[i], len + 1, sourceDisk, targetDisk);
            }

            // 为防止输出文件覆盖源文件,所以更改输出盘路径 也可自行设置其它路径
            File outPath = new File(file[i].getParent().replace(sourceDisk, targetDisk));
            File readfile = new File(file[i].getAbsolutePath());

            if (!readfile.isDirectory()) {
                String filename = readfile.getName(); // 读到的文件名称
                String absolutepath = readfile.getAbsolutePath(); // 文件的绝对路径
                if (absolutepath.endsWith(".png") ||
                        absolutepath.endsWith(".ico") ||
                        absolutepath.endsWith(".jpg") ||
                        absolutepath.endsWith(".dll") ||
                        absolutepath.endsWith(".exe") ||
                        absolutepath.endsWith(".jar") ||
                        absolutepath.endsWith(".zip") ||
                        absolutepath.endsWith(".rdb") ||
                        absolutepath.endsWith(".docx") ||
                        absolutepath.endsWith(".pdb")
                ) {
                    //.png  .ico .jpg .dll .exe .jar .zip  .rdb .docx .pdb
                    try {
                        copyFileUsingFileChannels(absolutepath, filename, i, outPath);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } else {
                    readFile(absolutepath, filename, i, outPath); // 调用 readFile

                }

            }
        }
    }

    /**
     * 读取目录下的文件
     *
     * @return
     */
    public static void readFile(String absolutepath, String filename,
                                int index, File outPath) {
        try {
            BufferedReader bufReader = new BufferedReader(new InputStreamReader(
                    new FileInputStream(absolutepath), "utf8")); // 数据流读取文件

            StringBuffer strBuffer = new StringBuffer();


            int line = 0;
            for (String temp = null; (temp = bufReader.readLine()) != null;
                 temp = null) {
                line++;
                if ((temp.indexOf(oldStr) != -1) &&
                        (temp.indexOf(oldStr) != -1)) { // 推断当前行是否存在想要替换掉的字符
                    temp = temp.replace(oldStr, newStr); // 此处进行替换

                    System.out.println(absolutepath + "\t\t\t\t\t\t\t\t\t\t\t" + "第" + line + "行" + "替换" + oldStr + "为" + newStr);
                }

                strBuffer.append(temp);
                strBuffer.append(System.getProperty("line.separator")); // 换行符
            }

            bufReader.close();

            if (outPath.exists() == false) { // 检查输出目录是否存在,若不存在先创建
                outPath.mkdirs();
                //System.out.println("已成功创建输出目录:" + outPath);
            }

            PrintWriter printWriter = new PrintWriter(outPath + File.separator + filename, "utf8"); // 替换后输出文件路径
            printWriter.write(strBuffer.toString().toCharArray()); //又一次写入
            printWriter.flush();
            printWriter.close();
            //System.out.println("第 " + (index + 1) + " 个文件   " + absolutepath +"  已成功输出到    " + outPath + "\\" + filename);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void copyFileUsingFileChannels(String absolutepath, String filename,
                                                 int index, File outPath) throws IOException {

        if (outPath.exists() == false) { // 检查输出目录是否存在,若不存在先创建
            outPath.mkdirs();
            //System.out.println("已成功创建输出目录:" + outPath);
        }

        FileChannel inputChannel = null;
        FileChannel outputChannel = null;
        try {
            inputChannel = new FileInputStream(absolutepath).getChannel();
            outputChannel = new FileOutputStream(outPath.getAbsolutePath() + File.separator + filename).getChannel();
            outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
        } finally {
            inputChannel.close();
            outputChannel.close();
        }
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
您好!我可以为您提供一个工具类来将一个XML文件写入指定的数据库。以下是示例代码: ```java import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilder; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import java.io.File; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; public class XMLToDatabaseUtil { public static void main(String argv[]) { String xmlFilePath = "path/to/xml/file"; String databaseUrl = "jdbc:mysql://localhost:3306/mydatabase"; String username = "root"; String password = "mypassword"; try { // Load JDBC driver Class.forName("com.mysql.jdbc.Driver"); // Connect to database Connection conn = DriverManager.getConnection(databaseUrl, username, password); // Create a prepared statement to insert data into the database String sql = "INSERT INTO mytable (name, email, phone) VALUES (?, ?, ?)"; PreparedStatement preparedStatement = conn.prepareStatement(sql); // Parse the XML file to extract information to be added to the database File file = new File(xmlFilePath); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(file); // Traverse the XML document and extract required data doc.getDocumentElement().normalize(); NodeList nodeList = doc.getElementsByTagName("person"); for (int i = 0; i < nodeList.getLength(); i++) { Element element = (Element) nodeList.item(i); String name = element.getAttribute("name"); String email = element.getElementsByTagName("email").item(0).getTextContent(); String phone = element.getElementsByTagName("phone").item(0).getTextContent(); // Set parameters in prepared statement and execute it preparedStatement.setString(1, name); preparedStatement.setString(2, email); preparedStatement.setString(3, phone); preparedStatement.executeUpdate(); } // Close prepared statement and database connection preparedStatement.close(); conn.close(); } catch (Exception e) { e.printStackTrace(); } } } ``` 请注意,您需要将“path/to/xml/file”替换为实际的XML文件路径,以及将“mydatabase”替换为您实际的数据库名称,“root”和“mypassword”替换为数据库的用户名和密码,以及将“mytable”替换为您要将数据添加到其中的实际数据库表名。 希望这有助于您将XML文件写入指定的数据库!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值