java 寫bat文件與執行bat文件

主要實現文件,文件夾的複製和刪除等

private void insertAndWrap(StringBuffer sb, String str) {
        sb.append(str);
        sb.append("\r\n");
    }

    private void writeBatFile(File batFile, String filePath, String newVersionPath) {
        StringBuffer sb = new StringBuffer();
        insertAndWrap(sb, "@echo off");
        insertAndWrap(sb, "color a");
        // 暫停2秒
        insertAndWrap(sb, "ping -n 2 127.0.0.1>nul");
        // 刪除老版本上的一部分文件
        insertAndWrap(sb, "del /f/s/q " + filePath + "\\*.dll");
        insertAndWrap(sb, "del /f/s/q " + filePath + "\\*.lib");
        insertAndWrap(sb, "del /f/s/q " + filePath + "\\*.h");
        insertAndWrap(sb, "rmdir /s/q " + filePath + "\\bin");
        insertAndWrap(sb, "rmdir /s/q " + filePath + "\\conf\\com");
        insertAndWrap(sb, "del /f/s/q " + filePath + "\\conf\\hibernate.cfg.xml");
        insertAndWrap(sb, "del /f/s/q " + filePath + "\\conf\\spring*.xml");
        insertAndWrap(sb, "del /f/s/q " + filePath + "\\conf\\ticketConfig.xml");
        insertAndWrap(sb, "rmdir /s/q " + filePath + "\\lib");
        // 暫停1秒
        insertAndWrap(sb, "ping -n 1 127.0.0.1>nul");
        // 將新版本上的文件複製到老版本上
        insertAndWrap(sb, "xcopy /y " + newVersionPath + "\\*.dll " + filePath + "");
        insertAndWrap(sb, "xcopy /y " + newVersionPath + "\\*.lib " + filePath + "");
        insertAndWrap(sb, "xcopy /y " + newVersionPath + "\\*.h " + filePath + "");
        insertAndWrap(sb, "md " + filePath + "\\bin");
        insertAndWrap(sb, "xcopy " + newVersionPath + "\\bin " + filePath + "\\bin /e");
        insertAndWrap(sb, "md " + filePath + "\\conf\\com");
        insertAndWrap(sb, "xcopy " + newVersionPath + "\\conf\\com " + filePath + "\\conf\\com /e");
        insertAndWrap(sb, "xcopy /y " + newVersionPath + "\\conf\\hibernate.cfg.xml " + filePath
                + "\\conf");
        insertAndWrap(sb, "xcopy /y " + newVersionPath + "\\conf\\spring*.xml " + filePath
                + "\\conf");
        insertAndWrap(sb, "xcopy /y " + newVersionPath + "\\conf\\ticketConfig.xml " + filePath
                + "\\conf");
        insertAndWrap(sb, "md " + filePath + "\\lib");
        insertAndWrap(sb, "xcopy /y " + newVersionPath + "\\lib " + filePath + "\\lib /e");
        insertAndWrap(sb, filePath.split(":")[0] + ":");
        insertAndWrap(sb, "cd " + filePath);
        insertAndWrap(sb, "start " + filePath + "\\run.bat");
        try {
            FileUtils.writeStringToFile(batFile, sb.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
如果要執行,只需要

private void startNewSoft(String batPath) {
        try {
            String cmd = "cmd /c start " + batPath;
            Runtime.getRuntime().exec(cmd);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

發佈了23 篇原創文章 · 獲贊 6 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章