[Java Basic Exercises] Multi-threaded IO stream operation to realize file copying (by analogy)

Foreword: Time waits for no one, it is spring suddenly, and early summer is approaching. However, I was surprised that my Java foundation was still weak. Although "the great pass is as solid as iron", I had to "surpass the mountain from the beginning". Laying a solid foundation is fundamental, and it is also extremely important for future work. Through continuous learning and understanding plus manual practice of code programs, it is the best choice for programming learning!

Topic : Copying files using multithreading. Enter the initial file path and the target folder path to realize the copy operation.

Ideas:

1. If you just want to copy the file, you can use the reNameTo() method of the file, but if the file includes folders, you can only do it through the file IO stream operation.

2. First, the most basic implementation traverses all files in a folder and packs them into a collection.

3. Enable multi-threading, establish a thread pool, and perform IO stream operations on files to copy files.

1. File traversal

1. Get all files

 public static List GetAllFiles(String SourceFile)//获取所有文件
    {
        List<File> FileList=new ArrayList<>();//文件列表
        File file=new File(SourceFile);//获取源文件
        if (file.exists()&&file.isDirectory()) {//如果文件存在且是文件夹形式则进行递归
            FileList = LongEegodic(file, FileList);
        }
        return FileList;
    }

2. Recursion

public static List LongEegodic(File file,List res)//递归获取文件、文件夹
    {
        File filelist[]=file.listFiles();
        if (filelist==null)//文件为空直接返回
            return null;
        for (File file1:filelist)
        {
            res.add(file1);//无论是文件夹还是文件都加入列表
            LongEegodic(file1,res);//递归,继续获取子文件
        }
        return res;
    }

2. The IO stream of the file realizes the copy operation of the file

  public static void Copy(File Source,File Target)//使用IO流进行文件的复制操作
    {
        FileInputStream Fis=null;//输入流
        FileOutputStream Fos=null;//输出流
        try {
            Fis=new FileInputStream(Source);
            Fos=new FileOutputStream(Target);
            byte buf[]=new byte[1024];//每次传送的字节数量
            int len=0;
            while ((len=Fis.read(buf))!=-1)//如果还有字节则继续传送
            {
                Fos.write(buf,0,len);//写入目标文件夹
            }
        }
        catch (Exception e)
        {
       e.printStackTrace();
        }
        finally {
            try {
                Fis.close();//关闭流
                Fos.flush();//刷新流
                Fos.close();
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }

3. Multi-threaded file copying

 public static void main(String args[])
    {
        Scanner scan=new Scanner(System.in);
        System.out.println("要复制的文件夹:");
        String SourceFilePath=scan.next();
        System.out.println("要复制到哪里去:");
        String TargetFilePath=scan.next();
        File SourceFile=new File(SourceFilePath);
        File TargetFile=new File(TargetFilePath);
         new  Thread(){//多线程实现文件的复制
           public void run() {
               if (SourceFile.isFile()) {
                   System.out.println("复制单个文件");
                   Copy(SourceFile, TargetFile);
               }
               else {
                List<File> FileLists=GetAllFiles(SourceFilePath);//获取全部文件
                   ExecutorService threadpool=Executors.newFixedThreadPool(20);//启用线程池,设定线程数量为20
                   for (File file:FileLists)
                   {
                       String PrimaryPath=file.getPath();//原文件路径
                       String NewPath=PrimaryPath.replace(SourceFile.getParent(),TargetFilePath+"/");//更改为新路径
                       System.out.println(PrimaryPath+ "变成了" + NewPath);
                       if (file.isDirectory())
                       {//文件夹则可以直接创建文件目录
                           new File(NewPath).mkdirs();
                       }
                       else {
                           threadpool.execute(new Runnable() {
                               @Override
                               public void run() {//重写方法
                                   File copyfile=new File(NewPath);
                                    copyfile.getParentFile().mkdirs();//先要有父文件夹
                                    Copy(file,copyfile);//复制文件
                               }
                           });
                       }
                   }
               }
           }
    }.start();
    }

4. Complete source code + running results

package FileTest;
import java.util.concurrent.Executors;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
public class Test6 {
    public static void main(String args[])
    {
        Scanner scan=new Scanner(System.in);
        System.out.println("要复制的文件夹:");
        String SourceFilePath=scan.next();
        System.out.println("要复制到哪里去:");
        String TargetFilePath=scan.next();
        File SourceFile=new File(SourceFilePath);
        File TargetFile=new File(TargetFilePath);
         new  Thread(){//多线程实现文件的复制
           public void run() {
               if (SourceFile.isFile()) {
                   System.out.println("复制单个文件");
                   Copy(SourceFile, TargetFile);
               }
               else {
                List<File> FileLists=GetAllFiles(SourceFilePath);//获取全部文件
                   ExecutorService threadpool=Executors.newFixedThreadPool(20);//启用线程池,设定线程数量为20
                   for (File file:FileLists)
                   {
                       String PrimaryPath=file.getPath();//原文件路径
                       String NewPath=PrimaryPath.replace(SourceFile.getParent(),TargetFilePath+"/");//更改为新路径
                       System.out.println(PrimaryPath+ "变成了" + NewPath);
                       if (file.isDirectory())
                       {//文件夹则可以直接创建文件目录
                           new File(NewPath).mkdirs();
                       }
                       else {
                           threadpool.execute(new Runnable() {
                               @Override
                               public void run() {//重写方法
                                   File copyfile=new File(NewPath);
                                    copyfile.getParentFile().mkdirs();//先要有父文件夹
                                    Copy(file,copyfile);//复制文件
                               }
                           });
                       }
                   }
               }
           }
    }.start();
    }
    public static void Copy(File Source,File Target)//使用IO流进行文件的复制操作
    {
        FileInputStream Fis=null;//输入流
        FileOutputStream Fos=null;//输出流
        try {
            Fis=new FileInputStream(Source);
            Fos=new FileOutputStream(Target);
            byte buf[]=new byte[1024];//每次传送的字节数量
            int len=0;
            while ((len=Fis.read(buf))!=-1)//如果还有字节则继续传送
            {
                Fos.write(buf,0,len);//写入目标文件夹
            }
        }
        catch (Exception e)
        {
       e.printStackTrace();
        }
        finally {
            try {
                Fis.close();//关闭流
                Fos.flush();//刷新流
                Fos.close();
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }
    public static List GetAllFiles(String SourceFile)//获取所有文件
    {
        List<File> FileList=new ArrayList<>();//文件列表
        File file=new File(SourceFile);//获取源文件
        if (file.exists()&&file.isDirectory()) {//如果文件存在且是文件夹形式则进行递归
            FileList = LongEegodic(file, FileList);
        }
        return FileList;
    }
    public static List LongEegodic(File file,List res)//递归获取文件、文件夹
    {
        File filelist[]=file.listFiles();
        if (filelist==null)
            return null;
        for (File file1:filelist)
        {
            res.add(file1);
            LongEegodic(file1,res);
        }
        return res;
    }
}

result:

It's not easy to post, I implore the big guys to raise your hands!


Likes: Likes are a kind of virtue, and they are the recognition of my creation by the bosses!


Comments: There is no white contact, it is the beginning of communication between you and me!


Collection: May you pick more, it is the appreciation of the bosses to me!

Guess you like

Origin blog.csdn.net/m0_55278347/article/details/130371451