使用线程从列表中复制文件

时间:2017-04-04 19:30:03

标签: java multithreading threadpool executorservice

我正在开发一个用四个线程复制文件的项目。

我创建List并存储要复制的文件名。 我想使用这4个线程一起工作,但我真的不知道如何让它发生。

public class CopyingFiles implements Runnable
{
 static File source = new File("C:\\test\\1\\");
 static File dest = new File("C:\\test\\2\\");

@Override
public void run()
{
    try
    {
        CopyingFromList(source, dest);
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
    catch (InterruptedException e)
    {
        e.printStackTrace();
    }
}

public static void CopyFile(File sourceFile, File destination) throws IOException
{

    InputStream inputStream = null;
    OutputStream outputStream = null;

    try {
        inputStream = new FileInputStream(sourceFile);
        outputStream = new FileOutputStream(destination);

        byte[] buffer = new byte[1024];


        int length;
        while ((length = inputStream.read(buffer)) > 0)
        {
            outputStream.write(buffer, 0 ,length);
        }
    } finally {
        if(inputStream != null)
        {
            inputStream.close();
        }

        if(inputStream != null)
        {
            outputStream.close();
        }
    }
}

public static void CopyingFromList(File source, File dest) throws IOException, InterruptedException
{
    List<String> fileList = FilesList.CreateFilesList(source);

    for(String file : fileList)
    {
        System.out.println(Thread.currentThread().getName() + " > " + FilesList.DestinationOfFile(source) + file + " > " + FilesList.DestinationOfFile(dest) + file );
        CopyFile(new File(FilesList.DestinationOfFile(source) + file), new File(FilesList.DestinationOfFile(dest) + file));
    }
}
}

AND SECOND CLASS

   public class FilesList
    {
    static File source = new File("C:\\test\\1\\");
    static File source1 = new File("C:\\test\\3\\");
    static File dest = new File("C:\\test\\2\\");
    static File dest1 = new File("C:\\test\\4\\");


    public static List<String> CreateFilesList(File source) throws InterruptedException, IOException
    {
        List<String> fileList = new ArrayList<>(Arrays.asList(source.list()));

        return fileList;
    }

    public static String DestinationOfFile(File source)
    {
        return new String(source + "\\");
    }

    public static void PrintWholeList(File source) throws IOException, InterruptedException
    {
        List<String> fileList = CreateFilesList(source);
        for(String file : fileList)
        {
           System.out.println(DestinationOfFile(source) + file);
        }
    }


    public static void main(String []args) throws IOException, InterruptedException
    {    /*
        //CopyingFiles.CopyFile(new File(source+"\\file1.txt"), new File(dest+"\\file1.txt"));
        //CopyingFiles.CopyingFromList(source,dest);

        CopyingFiles t1 = new CopyingFiles();
        CopyingFiles t2 = new CopyingFiles();
        CopyingFiles t3 = new CopyingFiles();
        CopyingFiles t4 = new CopyingFiles();

        t1.start();
        t2.start();
        t3.start();
        t4.start();
        */
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        System.out.println(Thread.activeCount());

        executorService.submit(() -> {
            try
            {
                CopyingFiles.CopyingFromList(source,dest);
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
            finally
            {
                executorService.shutdown();
            }
        });
    }
}

任何人都可以帮助我,或者展示一些其他方法来解决我的问题。

1 个答案:

答案 0 :(得分:0)

我实际上并没有解决问题所在。这个适用于我(这几乎是你的程序,只是清理了一下):

package multicp;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static java.nio.file.StandardCopyOption.COPY_ATTRIBUTES;

/**
 * Copy files using threads.
 */
public class Multicp {
    public static void main(String[] args) {
        // List of source/dest pairs ("tasks")
        List<CopierCallable<Void>> opsList = new ArrayList<>();
        opsList.add(new CopierCallable<>(Paths.get("f1src.dat"), Paths.get("f1dest.dat")));
        opsList.add(new CopierCallable<>(Paths.get("f2src.dat"), Paths.get("f2dest.dat")));
        opsList.add(new CopierCallable<>(Paths.get("f3src.dat"), Paths.get("f3dest.dat")));
        opsList.add(new CopierCallable<>(Paths.get("f4src.dat"), Paths.get("f4dest.dat")));

        ExecutorService execSvc = Executors.newFixedThreadPool(2); // 4 in your case. 2 is just for testing
        try {
            execSvc.invokeAll(opsList);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            execSvc.shutdown();
        }
    }

}

/**
 * Performs actual copying from one source to one destination.
 */
class CopierCallable<Void> implements Callable<Void> {
    private Path pathFrom;
    private Path pathTo;

    public CopierCallable(Path pathFrom, Path pathTo) {
        this.pathFrom = pathFrom;
        this.pathTo = pathTo;
    }

    @Override
    public Void call() {
        try {
            // REPLACE_EXISTING is destructive, uncomment at your own risk
            Files.copy(pathFrom, pathTo, COPY_ATTRIBUTES /*, REPLACE_EXISTING*/);
            System.out.println(pathFrom + " copied");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

我可以看到文件在组中同时被复制(2用于测试;用4替换,但它会使初始化代码更大而无利可图)。