java - 在java中分几个部分或片段下载文件

标签 java multithreading concurrency download

我正在尝试以多段方式下载java中的文件(即,将其分为几个部分并在单独的线程中并行下载每个部分),但是当我使用下面的代码时,似乎每个线程都在下载整个文件而不是其中的一部分,但是当它完成时,文件被正确下载。

请注意,“downloadedSizeCombined”是所有线程下载的所有字节的总和,ArrayList“downloadedSize”跟踪单个线程下载的字节。

此方法位于扩展 SwingWorker 的 Download 类中。

public Void doInBackground() {
    ExecutorService es = Executors.newCachedThreadPool();
    for (int i = 0; i < MAX_NUMBER_OF_PARTS; i++) {
        int numOfThePart = i;
        es.execute(new Runnable() {
            @Override
            public void run() {
                RandomAccessFile file = null;
                InputStream stream = null;

                try {
                    while (Download.this.getStatus() == WAITINGLIST) {
                        Thread.sleep(1);
                    }
                    // Open connection to URL.
                    HttpURLConnection connection =
                        (HttpURLConnection) url.openConnection();

                    // Specify what portion of file to download.
                    int startByte = numOfThePart * sizeOfFile / MAX_NUMBER_OF_PARTS;
                    int endByte = ((numOfThePart + 1) * sizeOfFile / MAX_NUMBER_OF_PARTS) - 1;
                    if (numOfThePart == MAX_NUMBER_OF_PARTS)
                        endByte = ((numOfThePart + 1) * sizeOfFile / MAX_NUMBER_OF_PARTS);
                    connection.setRequestProperty("Range",
                        "bytes=" + ((startByte + downloadedSize.get(numOfThePart))) + "-" + endByte);

                    // Connect to server.
                    connection.connect();

                    // Check for valid content length.
                    int contentLength = connection.getContentLength();
                    if (contentLength < 1) {
                        System.out.println("1");
                    }

                    /* Set the size for this download if it
                       hasn't been already set. */
                    if (sizeOfFile == -1) {
                        sizeOfFile = contentLength;
                    }

                    file = new RandomAccessFile(new File(s.getCurrentDirectory(), getFileName(url)),
                        "rw");
                    file.seek(startByte + downloadedSize.get(numOfThePart));

                    fileLocation = new File(s.getCurrentDirectory(), getFileName(url));

                    stream = connection.getInputStream();
                    while (status == CURRENT) {
                        file.seek(startByte + downloadedSize.get(numOfThePart));

                        byte buffer[];

                        buffer = new byte[MAX_BUFFER_SIZE];

                        // Read from server into buffer.
                        int read = stream.read(buffer);

                        if (read == -1)
                            break;

                        // Write buffer to file.
                        file.write(buffer, 0, read);
                        downloadedSizeCombined += read;
                        downloadedSize.set(numOfThePart, downloadedSize.get(numOfThePart) + read);

                        publish(numOfThePart);
                        while (status == PAUSED) {
                            Thread.sleep(1);
                        }

                    }

                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    // Close file.
                    if (file != null) {
                        try {
                            file.close();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    // Close connection to server.
                    if (stream != null) {
                        try {
                            stream.close();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        });
    }
    return null;
}

提前致谢。

最佳答案

我们不能使用UDP连接吗?因此,如果我们使用 DatagramSocket 类,它无论如何都会以数据包的形式发送数据。尝试这个。 很快就会回来讨论这个问题..

关于java - 在java中分几个部分或片段下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50652005/

相关文章:

java - 在Java中组合注解

java - 无边距打印

c++ - ThreadSanitizer (tsan) - 来自共享库的有意义的信息

Java 并发迭代 : Divide and Conquer vs Runnable for each item

java - JScrollPane setViewPosition After "Zoom"

c++ - 避免 local() 调用 tbb enumerable_thread_specific 变量

java - android等待服务器响应

concurrency - Celery: worker 数量与并发性

java - 当线程池大小小于执行的任务数时,使用 newFixedThreadPool 的多线程程序不会正常运行

java - 我如何告诉 Spring 使用 Java 映射来解析属性占位符?