[记录]文件下载初级程序
package com.example.demo.io.github.viscent.mtia.ch1;
import com.example.demo.io.github.viscent.mtia.util.Debug;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.io.UnsupportedEncodingException;
import java.net.*;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
public class FileDownloaderAppTest {
public static void main(String[] args) throws UnsupportedEncodingException {
args = new String[]{"https://download.daokeyuedu.com/docbox/%E7%A8%BB%E5%A3%B3%E9%98%85%E8%AF%BB%E5%99%A8%E5%AE%89%E8%A3%85%E7%A8%8B%E5%BA%8F.exe"};
String dest = "C:/Users/lan/Desktop";
for (String arg : args) {
String url = URLDecoder.decode(arg, "utf-8");
new Thread(new DowloadFileR(url, dest)).start();
}
System.out.println("File Download Done!");
}
static class DowloadFileR implements Runnable {
private String source;
private String dest;
public DowloadFileR(String source, String dest) {
this.source = source;
this.dest = dest;
}
;
@Override
public void run() {
try {
this.dowloadFile(source, dest);
} catch (IOException e) {
e.printStackTrace();
}
}
private void dowloadFile(String source, String dest) throws IOException {
InputStream inputStream = null;
HttpURLConnection urlConnection = null;
String name = source.substring(source.lastIndexOf("/") + 1);
dest = dest + "/" + name;
try (RandomAccessFile randomAccessFile = new RandomAccessFile(dest, "rw")) {
URL url = new URL(source);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
if (2 != urlConnection.getResponseCode() / 100) {
throw new IOException("Request err: " + urlConnection.getResponseCode());
}
if (0 == urlConnection.getContentLength()) {
Debug.info("Nothing to be downloaded:" + source);
return;
}
;
inputStream = urlConnection.getInputStream();
ReadableByteChannel inChannel = Channels.newChannel(inputStream);
FileChannel channel = randomAccessFile.getChannel();
ByteBuffer buf = ByteBuffer.allocate(8192);
while (-1 != inChannel.read(buf)) {
buf.flip();
channel.write(buf);
buf.clear();
}
} finally {
if (inputStream != null) {
inputStream.close();
}
if (urlConnection != null) {
urlConnection.disconnect();
}
}
}
;
}
}