Hôm nay chúng ta sẽ học cách tải tệp từ URL trong Java. Chúng ta có thể sử dụng method java.net.URL
openStream()
để tải file từ URL trong chương trình Java. Chúng ta cũng có thể dùng Java NIO Channels hoặc Java IO InputStream để đọc dữ liệu từ URL open stream và sau đó lưu nó vào file.
Tải tệp từ URL trong Java
Đây là một chương trình ví dụ đơn giản về cách download file từ URL trong Java. Nó minh họa cả hai cách để download file từ URL trong Java. Tên file: JavaDownloadFileFromURL.java
package com.journaldev.files;
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.journaldev.com/sitemap.xml>";
try {
downloadUsingNIO(url, "/Users/pankaj/sitemap.xml");
downloadUsingStream(url, "/Users/pankaj/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: Trong phương pháp này để download file từ URL trong Java, chúng ta dùng URL openStream
để tạo input stream. Sau đó dùng FileOutputStream để đọc dữ liệu từ input stream và ghi ra file. downloadUsingNIO: Trong phương pháp download file từ URL này, chúng ta tạo byte channel từ dữ liệu URL stream. Sau đó dùng FileOutputStream để ghi dữ liệu ra file.
Bạn có thể sử dụng bất kỳ phương pháp nào trong số này để tải file từ URL trong Java. Nếu bạn quan tâm đến hiệu năng, hãy thử phân tích bằng cách dùng cả hai phương pháp và xem cái nào phù hợp hơn với nhu cầu của bạn.
Bạn có thể tham khảo thêm các ví dụ về Java IO trong GitHub Repository của chúng tôi.