Salinan kode adalah sebagai berikut:
paket com.hongyuan.test;
impor java.io.file;
impor java.io.fileoutputStream;
impor java.io.ioException;
impor java.io.inputstream;
impor java.io.outputStream;
impor java.net.httpurlconnection;
impor java.net.malformedurlexception;
impor java.net.url;
impor java.net.urldecoder;
kelas publik fileDownload {
string final statis public local_path = "d:/";
public static void main (string [] args) {
// alamat file yang akan diunduh
Rangkaian fileUrl = "http://211.162.55.16/cdn.baidupcs.com/file/6a73dab7c03023a9835cc73 826-250528-130564002 & waktu = 1397293108 & tanda = fdtaxer-dcb740ccc5511e5e8fedcff06b08120 3-mqkoerdtxpyqwwyjki%2bxkjpxn5k%3d & to = cb & fm = n, b, u, nc & newver = 1 & kedaluwarsa = 1397297563 & rt = sh & r = 854979042 & logid = 17517171591592 %A8%8b%E5%BA%8f%E8%AE% Jadilah%E8%AE%A1%20%E7%AC%AC5%E7%89%88.pdf & wshc_tag = 0 & wsiphost = ipdbm ";
Inputstream in = null;
OutputStream out = null;
HttpurlConnection conn = null;
String fileName = null;
mencoba {
// Inisialisasi koneksi
Url url = url baru (fileurl);
conn = (httpurlConnection) url.openconnection ();
Conn.setDoInput (true);
Conn.SetDoOutput (true);
// Dapatkan nama file
String disposition = conn.getheaderfield ("konten-disposisi");
if (disposisi! = null &&! "". Equals (disposisi)) {
// Dapatkan nama file dari awal
nama file = disposisi.
}kalau tidak{
// Dapatkan nama file dari alamat
filename = fileurl.substring (fileurl.lastIndexof ("/")+1);
}
if (fileName! = null &&! "". Equals (fileName)) {
// decode nama file
fileName = urldecoder.decode (nama file, "UTF-8");
}kalau tidak{
// Jika nama file tidak dapat diambil, generasi acak akan dihasilkan
filename = "file _"+(int) (math.random ()*10);
}
// Baca data
if (conn.getResponsecode () == httpurlconnection.http_ok) {
byte [] buffer = byte baru [2048];
di = conn.getInputStream ();
out = FileOutputStream baru (file baru (local_path, fileName));
Int Count = 0;
int selesai = 0;
int size = conn.getContentLength ();
while ((count = in.read (buffer))! =-1) {
if (count! = 0) {
out.write (buffer, 0, count);
selesai+= hitung;
System.out.printf ("########################################## ################# (-->%1 $ .2f %%/n ", (ganda) selesai/ukuran*100);
}kalau tidak{
merusak;
}
}
}
} catch (Malformedurlexception e) {
e.printstacktrace ();
} catch (ioException e) {
e.printstacktrace ();
} Akhirnya{
mencoba {
out.close ();
melampirkan();
Conn.Disconnect ();
} catch (ioException e) {
e.printstacktrace ();
}
}
}
}