基于UDP的文件下载
构建连接
首先我们需要获取所需的文件资源所在的地址,然后根据地址创建URL对象,再通过对象获取文件所在路径以及文件名,为后来的下载到本机做好准备。
同时获取到文件的输出流。
(last.indexof("/") 获取“”/“”最后一次出现的位置)
target是定义好的参数,是下载的目标文件名。
URL url1 = new URL(url);
String path = url1.getPath();
int index = path.lastIndexOf("/");
String fname = path.substring(index+1);
target = new File(target, fname);
OutputStream os = new FileOutputStream(target);
根据创建好的URL对象建立连接(openConnection()),然后判断连接是不是好的,是的话开启下载任务。
下载使用到了流的知识,获取到连接的输入流开始下载
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection)url1.openConnection();
conn.setRequestMethod("GET");
int statecode = conn.getResponseCode();
if (statecode == HttpURLConnection.HTTP_OK) {
InputStream is = conn.getInputStream();
byte[] b =new byte[1024];
int len =0;
while ((len = is.read(b)) != -1) {
os.write(b, 0, len);
}
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
os.close();
conn.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
try里的异常请捕获,不要抛出。
测试
选开始测试需要的网址,下面是全部代码,网址自选,因为这是一个耗时的项目,所以我们采用线程来减少消耗。
public void download(String url, File target) throws MalformedURLException, FileNotFoundException {
URL url1 = new URL(url);
String path = url1.getPath();
int index = path.lastIndexOf("/");
String fname = path.substring(index+1);
target = new File(target, fname);
OutputStream os = new FileOutputStream(target);
new Thread(()->{
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection)url1.openConnection();
conn.setRequestMethod("GET");
int statecode = conn.getResponseCode();
if (statecode == HttpURLConnection.HTTP_OK) {
InputStream is = conn.getInputStream();
byte[] b =new byte[1024];
int len =0;
while ((len = is.read(b)) != -1) {
os.write(b, 0, len);
}
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
os.close();
conn.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
public static void main(String[] args) throws MalformedURLException, FileNotFoundException {
new FileDownload().download("http://*****.*******.***/musics/1592383934192.mp3", new File("f:\\"));
}