用Java下载和重新上传文件的最快方法是什么?

时间:2018-10-24 17:32:34

标签: java

我想使用标准Java API下载并重新上传文件(大小接近1 GB)。当前的实现是:

private void transfer(String sourceUrl, String targetUrl, long size) throws IOException {
    logger.info("Copying " + sourceUrl + " to " + targetUrl);
    HttpsURLConnection conn = (HttpsURLConnection) new URL(targetUrl).openConnection();
    conn.setDoOutput(true);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Length", Long.toString(size));
    try (InputStream inputStream = new URL(sourceUrl).openStream();
         OutputStream outputStream = conn.getOutputStream()) {
        byte[] buf = new byte[1 << 20];
        int read;
        long total = 0;
        while ((read = inputStream.read(buf)) != -1) {
            outputStream.write(buf, 0, read);
            total += read;
            logger.info(total + "/" + size + " " + (total * 100 / size) + "%");
        }
        outputStream.flush();
    }
}

但是,与本机应用程序相比,它运行缓慢。我试图增加缓冲区的大小。但这没有帮助。我该怎么做才能提高这种方法的性能?

任何人都可以通过多线程示例或NIO示例来帮助我提高性能吗?

0 个答案:

没有答案