Java從URL下載文件


Java從URL下載文件

使用java.net.URL openStream()方法從java程序中的URL下載文件。也可以使用Java NIO Channels或Java IO InputStream從URL打開流中讀取數據,然后將它保存到文件中。
下面是從指定URL下載的簡單Java程序。它演示了如何在java中從指定URL下載文件的兩種方法。

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;

public class JavaDownloadFileFromURL {

    public static void main(String[] args) {
        String url = "https://www.yiibai.com/index.html";

        try {
            downloadUsingNIO(url, "D:/users/maxsu/sitemap.xml");

            downloadUsingStream(url, "D:/users/maxsu/sitemap_stream.xml");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void downloadUsingStream(String urlStr, String file) throws IOException{
        URL url = new URL(urlStr);
        BufferedInputStream bis = new BufferedInputStream(url.openStream());
        FileOutputStream fis = new FileOutputStream(file);
        byte[] buffer = new byte[1024];
        int count=0;
        while((count = bis.read(buffer,0,1024)) != -1)
        {
            fis.write(buffer, 0, count);
        }
        fis.close();
        bis.close();
    }

    private static void downloadUsingNIO(String urlStr, String file) throws IOException {
        URL url = new URL(urlStr);
        ReadableByteChannel rbc = Channels.newChannel(url.openStream());
        FileOutputStream fos = new FileOutputStream(file);
        fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
        fos.close();
        rbc.close();
    }

}

downloadUsingStream:在這個從URL下載java文件的方法中,使用URL openStream方法來創建輸入流。然后使用文件輸出流從輸入流中讀取數據並寫入文件。
downloadUsingNIO:在這個URL方法的下載文件中,從URL流數據創建字節通道。然后使用文件輸出流將其寫入文件。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM