Java多连接下载文件

发布于 2024-08-30 13:33:08 字数 2493 浏览 1 评论 0原文

我想在下面的代码中添加多个连接以便能够更快地下载文件。有人可以帮助我吗?提前致谢。

public void run() {
    RandomAccessFile file = null;
    InputStream stream = null;

    try {
        // Open connection to URL.
        HttpURLConnection connection =
                (HttpURLConnection) url.openConnection();

        // Specify what portion of file to download.
        connection.setRequestProperty("Range",
                "bytes=" + downloaded + "-");

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

        // Make sure response code is in the 200 range.
        if (connection.getResponseCode() / 100 != 2) {
            error();
        }

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

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

        // Open file and seek to the end of it.
        file = new RandomAccessFile("C:\\"+getFileName(url), "rw");
        file.seek(downloaded);

        stream = connection.getInputStream();
        while (status == DOWNLOADING) {
            /* Size buffer according to how much of the
            file is left to download. */
            byte buffer[];
            if (size - downloaded > MAX_BUFFER_SIZE) {
                buffer = new byte[MAX_BUFFER_SIZE];
            } else {
                buffer = new byte[size - downloaded];
            }

            // Read from server into buffer.
            int read = stream.read(buffer);
            if (read == -1) {
                break;
            }

            // Write buffer to file.
            file.write(buffer, 0, read);
            downloaded += read;
            stateChanged();
        }

        /* Change status to complete if this point was
        reached because downloading has finished. */
        if (status == DOWNLOADING) {
            status = COMPLETE;
            stateChanged();
        }
    } catch (Exception e) {
        error();
    } finally {
        // Close file.
        if (file != null) {
            try {
                file.close();
            } catch (Exception e) {
            }
        }

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

I was wanting to add multiple connections in the code below to be able to download files faster. Could someone help me? Thanks in advance.

public void run() {
    RandomAccessFile file = null;
    InputStream stream = null;

    try {
        // Open connection to URL.
        HttpURLConnection connection =
                (HttpURLConnection) url.openConnection();

        // Specify what portion of file to download.
        connection.setRequestProperty("Range",
                "bytes=" + downloaded + "-");

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

        // Make sure response code is in the 200 range.
        if (connection.getResponseCode() / 100 != 2) {
            error();
        }

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

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

        // Open file and seek to the end of it.
        file = new RandomAccessFile("C:\\"+getFileName(url), "rw");
        file.seek(downloaded);

        stream = connection.getInputStream();
        while (status == DOWNLOADING) {
            /* Size buffer according to how much of the
            file is left to download. */
            byte buffer[];
            if (size - downloaded > MAX_BUFFER_SIZE) {
                buffer = new byte[MAX_BUFFER_SIZE];
            } else {
                buffer = new byte[size - downloaded];
            }

            // Read from server into buffer.
            int read = stream.read(buffer);
            if (read == -1) {
                break;
            }

            // Write buffer to file.
            file.write(buffer, 0, read);
            downloaded += read;
            stateChanged();
        }

        /* Change status to complete if this point was
        reached because downloading has finished. */
        if (status == DOWNLOADING) {
            status = COMPLETE;
            stateChanged();
        }
    } catch (Exception e) {
        error();
    } finally {
        // Close file.
        if (file != null) {
            try {
                file.close();
            } catch (Exception e) {
            }
        }

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

一城柳絮吹成雪 2024-09-06 13:33:08

您可以使用线程。

将下载和更新 RandomAccessFile 的代码放入 Thread/Runnable 中,并启动它的多个实例。

使用全局计数器(同步访问)来跟踪有多少线程完成下载,并让主线程等待,直到所有线程都增加计数器后再关闭文件。

确保同步对 RandomAccessFile 的所有访问,以便线程 A 在线程 B 写入文件的另一部分时无法调用 seek(somePosition)

You could use threads.

Put the code for downloading and updating the RandomAccessFile in a Thread/Runnable and start multiple instances of it.

Use a global counter (synchronized access) to keep track of how many threads finished downloading, and make the main thread wait until all threads have increased the counter before closing the file.

Make sure to synchronize all access to the RandomAccessFile, so that thread A can not call seek(somePosition) while thread B is writing to another part of the file.

左秋 2024-09-06 13:33:08

确保你描述了你的想法。多个线程的开销以及它们之间的协调可能会使您的代码变慢。
除非您确定这是瓶颈,否则不要这样做,代码复杂性会增加并且调试这很重要。

Make sure you profile what you come up with. It is possible that the overhead of multiple threads and the coordination between them could make you code slower.
Do not do this unless you are certain this is a bottleneck, the code complexity will increase and debugging this is non-trivial.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文