Java多线程实现文件上传下载

在Java中实现多线程文件上传和下载可以提高文件传输的效率。

一、多线程文件上传

多线程文件上传通常包括以下步骤:

  1. 创建一个文件上传任务,将文件拆分成多个块,并为每个块创建一个线程进行上传。
  2. 在服务器端接收这些块并将它们组合成完整的文件。
  3. 确保所有线程都完成上传后才标记上传任务完成。
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class MultiThreadFileUpload {
    public static void main(String[] args) {
        String fileToUpload = "D:\path\file.txt";
        String serverUrl = "http://localhost:8080/upload";

        int numThreads = 4; // 设置线程数量

        FileUploader[] uploaders = new FileUploader[numThreads];

        try {
            File file = new File(fileToUpload);
            long fileSize = file.length();
            long chunkSize = fileSize / numThreads;

            for (int i = 0; i < numThreads; i++) {
                long startByte = i * chunkSize;
                long endByte = (i == numThreads - 1) ? fileSize - 1 : (i + 1) * chunkSize - 1;

                uploaders[i] = new FileUploader(file, serverUrl, startByte, endByte);
                uploaders[i].start();
            }

            // 等待所有线程完成上传
            for (int i = 0; i < numThreads; i++) {
                uploaders[i].join();
            }

            System.out.println("文件上传完成");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

class FileUploader extends Thread {
    private File file;
    private String serverUrl;
    private long startByte;
    private long endByte;

    public FileUploader(File file, String serverUrl, long startByte, long endByte) {
        this.file = file;
        this.serverUrl = serverUrl;
        this.startByte = startByte;
        this.endByte = endByte;
    }

    @Override
    public void run() {
        try {
            URL url = new URL(serverUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/octet-stream");
            connection.setRequestProperty("Range", "bytes=" + startByte + "-" + endByte);

            FileInputStream fileInputStream = new FileInputStream(file);
            fileInputStream.skip(startByte);

            OutputStream outputStream = connection.getOutputStream();
            byte[] buffer = new byte[4096];
            int bytesRead;

            while ((bytesRead = fileInputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }

            fileInputStream.close();
            outputStream.close();

            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_PARTIAL) {
                System.out.println("上传成功: " + startByte + " - " + endByte);
            } else {
                System.out.println("上传失败: " + startByte + " - " + endByte);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

以上例子将文件分成多个块并使用不同的线程上传每个块,然后在服务器端将这些块组合成完整的文件。

二、多线程文件下载

  1. 获取要下载的文件的总大小。
  2. 创建多个线程,每个线程负责下载文件的一部分。
  3. 将所有下载的部分合并成完整的文件。
  4. import java.io.*;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.util.concurrent.CountDownLatch;
    
    public class MultiThreadFileDownload {
        public static void main(String[] args) {
            String fileUrl = "http://localhost:8080/download/file.txt";
            String destinationPath = "D:\path\file.txt";
            int numThreads = 4; // 设置线程数量
    
            try {
                URL url = new URL(fileUrl);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                int fileSize = connection.getContentLength();
    
                CountDownLatch latch = new CountDownLatch(numThreads);
                long chunkSize = fileSize / numThreads;
    
                for (int i = 0; i < numThreads; i++) {
                    long startByte = i * chunkSize;
                    long endByte = (i == numThreads - 1) ? fileSize - 1 : (i + 1) * chunkSize - 1;
    
                    FileDownloader downloader = new FileDownloader(fileUrl, destinationPath, startByte, endByte, latch);
                    new Thread(downloader).start();
                }
    
                latch.await(); // 等待所有线程完成下载
                System.out.println("文件下载完成");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    
    class FileDownloader implements Runnable {
        private String fileUrl;
        private String destinationPath;
        private long startByte;
        private long endByte;
        private CountDownLatch latch;
    
        public FileDownloader(String fileUrl, String destinationPath, long startByte, long endByte, CountDownLatch latch) {
            this.fileUrl = fileUrl;
            this.destinationPath = destinationPath;
            this.startByte = startByte;
            this.endByte = endByte;
            this.latch = latch;
        }
    
        @Override
        public void run() {
            try {
                URL url = new URL(fileUrl);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestProperty("Range", "bytes=" + startByte + "-" + endByte);
    
                InputStream inputStream = connection.getInputStream();
                RandomAccessFile outputFile = new RandomAccessFile(destinationPath, "rw");
                outputFile.seek(startByte);
    
                byte[] buffer = new byte[4096];
                int bytesRead;
    
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputFile.write(buffer, 0, bytesRead);
                }
    
                inputStream.close();
                outputFile.close();
                latch.countDown(); // 通知主线程下载完成
    
                System.out.println("下载完成: " + startByte + " - " + endByte);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    

    以上例子将文件分成多个块,并使用不同的线程下载每个块,然后将这些部分合并成完整的文件。注意使用RandomAccessFile来确保多线程下载时不会覆盖文件的其他部分。另外,使用CountDownLatch来等待所有线程完成下载。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
Java 中进行文件上传下载时,可以使用多线程来加速传输速度和提高效率。下面是一个简单的示例代码,实现了同时上传下载多个文件的功能: 文件上传: ```java import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; import java.net.Socket; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class FileUploader { private final static String SERVER_IP = "127.0.0.1"; private final static int SERVER_PORT = 9999; private static class UploadTask implements Runnable { private File file; public UploadTask(File file) { this.file = file; } @Override public void run() { try (Socket socket = new Socket(SERVER_IP, SERVER_PORT); FileInputStream fis = new FileInputStream(file); OutputStream os = socket.getOutputStream()) { byte[] buffer = new byte[1024]; int len; while ((len = fis.read(buffer)) != -1) { os.write(buffer, 0, len); } os.flush(); System.out.println("File uploaded: " + file.getName()); } catch (IOException e) { e.printStackTrace(); } } } public static void main(String[] args) { String[] files = {"/path/to/file1", "/path/to/file2", "/path/to/file3"}; ExecutorService executorService = Executors.newFixedThreadPool(3); for (String file : files) { executorService.submit(new UploadTask(new File(file))); } executorService.shutdown(); } } ``` 文件下载: ```java import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.ServerSocket; import java.net.Socket; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class FileDownloader { private final static int SERVER_PORT = 9999; private static class DownloadTask implements Runnable { private String fileName; public DownloadTask(String fileName) { this.fileName = fileName; } @Override public void run() { try (Socket socket = new Socket("localhost", SERVER_PORT); InputStream is = socket.getInputStream(); FileOutputStream fos = new FileOutputStream(fileName)) { byte[] buffer = new byte[1024]; int len; while ((len = is.read(buffer)) != -1) { fos.write(buffer, 0, len); } fos.flush(); System.out.println("File downloaded: " + fileName); } catch (IOException e) { e.printStackTrace(); } } } public static void main(String[] args) { String[] files = {"file1", "file2", "file3"}; ExecutorService executorService = Executors.newFixedThreadPool(3); try (ServerSocket serverSocket = new ServerSocket(SERVER_PORT)) { while (true) { Socket socket = serverSocket.accept(); InputStream is = socket.getInputStream(); byte[] buffer = new byte[1024]; int len; StringBuilder sb = new StringBuilder(); while ((len = is.read(buffer)) != -1) { sb.append(new String(buffer, 0, len)); } String fileName = sb.toString(); executorService.submit(new DownloadTask(fileName)); } } catch (IOException e) { e.printStackTrace(); } finally { executorService.shutdown(); } } } ``` 在这个示例中,上传下载都是通过 Socket 来实现的。在上传时,每个文件都会启动一个线程,将文件的内容写入到 Socket 的输出流中,发送给服务器。在下载时,服务器会监听指定的端口,并接收来自客户端的请求。每次接收到请求后,服务器会启动一个线程,读取客户端发送的文件名,并将文件的内容写入到 Socket 的输出流中,发送给客户端。这样就可以实现同时上传下载多个文件的效果了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

境里婆娑

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值