Java多线程可以实现文件的复制。下面是一个简单的示例代码:

import java.io.*;

public class FileCopy {

    public static void main(String[] args) {
        File sourceFile = new File("source.txt");
        File targetFile = new File("target.txt");

        Thread copyThread = new Thread(new CopyTask(sourceFile, targetFile));
        copyThread.start();
    }

    static class CopyTask implements Runnable {
        private File sourceFile;
        private File targetFile;

        public CopyTask(File sourceFile, File targetFile) {
            this.sourceFile = sourceFile;
            this.targetFile = targetFile;
        }

        @Override
        public void run() {
            try {
                FileInputStream fis = new FileInputStream(sourceFile);
                FileOutputStream fos = new FileOutputStream(targetFile);

                byte[] buffer = new byte[1024];
                int length;
                while ((length = fis.read(buffer)) > 0) {
                    fos.write(buffer, 0, length);
                }

                fis.close();
                fos.close();
                System.out.println("文件复制完成!");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

以上代码创建了一个CopyTask类,实现了Runnable接口,并在run()方法中执行了文件复制的操作。在main()方法中,创建一个CopyTask实例并传入源文件和目标文件,然后创建一个线程并启动,即可实现文件的复制。

请注意,以上代码仅仅是一个简单的示例,实际应用中可能需要考虑更多的情况,比如文件不存在的处理、线程同步等

java多线程实现复制

原文地址: http://www.cveoy.top/t/topic/is8x 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录