有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

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

我创建列表并将要复制的文件名存储在其中。 我想用这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));
    }
}
}

二等舱

   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) 个答案

  1. # 1 楼答案

    我真的不明白问题出在哪里。这一个对我很有用(它几乎就是你的程序,只是清理了一点):

    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复制,但这会使初始化代码变得更大,毫无益处)