golang copy folders and generate multiple files in batches

package main
import (
var (
srcDir string //source folder path
srctoDir string //target folder path
jishu int //Number of copied files
qty int //Number of folders
dirst []string // split file relative path
srctoName string //Absolute path of target file
oldFile string //Absolute path to source file
err error //error
func main() {
fmt.Println("Input source folder path:")
fmt.Println("Enter destination folder path:")
fmt.Println("Input quantity: ")
jishu = 0
pathSeparator := string(os.PathSeparator) //path separator
listAllFileByName(pathSeparator, srcDir)
fmt.Printf("Completed copying %v files, press Enter to exit!\n", jishu)
fmt.Scanln(&srcDir) //Pause after completion to prevent direct closing, no information can be seen, and then close after pressing Enter.
func listAllFileByName(pathSeparator string, fileDir string) {
files, _ := ioutil.ReadDir(fileDir) //read directory
for _, onefile := range files { // Traverse the files in the directory
if onefile.IsDir() { //It is a folder, continue to traverse recursively
listAllFileByName(pathSeparator, fileDir+pathSeparator+onefile.Name())
} else { //is a file
oldFile = fmt.Sprintf("%s%s%s", fileDir, pathSeparator, onefile.Name()) //Splicing the absolute path of the source file
dirst = strings.Split(oldFile, srcDir)
fmt.Println(dirst[1]) //Split relative path
//dirst[1]: remove the relative directory of srcDir
for i := 0; i < qty; i++ {
srctoName = fmt.Sprintf("%s%d%s", srctoDir, i, dirst[1]) //The absolute path of the splicing target file
_, err = os.Lstat(srctoName) //target file information, determine whether the target file exists (only determine whether there is a file with the same file name)
if err != nil {
//When the target file does not exist, copy the file to the target file
fileCopy(oldFile, srctoName, onefile.Name())
func fileCopy(oldFile, newFile, srctoDir string) {
toPath := strings.Split(newFile, srctoDir)
_, err = os.Lstat(toPath[0]) //The directory where the target file is located
if err != nil { //The directory does not exist, create the directory
err = os.MkdirAll(toPath[0], 0777)
input, err := ioutil.ReadFile(oldFile) //read source file
if err != nil {
err = ioutil.WriteFile(newFile, input, 0777) //Write the source file to the target file
if err != nil {
fmt.Println(newFile) //Output the absolute path of the copied target file
jishu++ //counter+1

Leave a Reply

Your email address will not be published. Required fields are marked *