分享一个通过原生的Java代码下载网络资源文件方法,使用URL类连接上网络服务器通过多线程使用I/O流的方式下载文件。
流程:
- 获取到资源的大小及各项参数
- 使用RandomAccessFile类生成对应大小的文件用于防止空间不足
- 启动下载任务线程,传入线程号等参数
- 下载线程与服务器建立连接,获取到对应的I/O流,将传入的字节写入到下载的本地文件中
线程工作示意图:
代码部分:
主程序文章来源:https://www.toymoban.com/news/detail-504795.html
import jdk.management.resource.NotifyingMeter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicLong;
public class Download{
public static void main(String[] args) throws IOException {
//1.待下载文件大小
String url="http://dl.baofeng.com/baofeng5/bf5_new.exe";
long fileSize=getFileSize(url);
System.out.println("下载的文件大小:"+fileSize);
String newFileName=getNewFileName(url);
System.out.println(newFileName);
String newFilePath=getNewFilePath(newFileName);
System.out.println(newFilePath);
//创建空文件
createNewFile(fileSize,newFilePath);
//获取cpu数
int threadSize=Runtime.getRuntime().availableProcessors();
//计算每个线程要下载的大小
long sizePerThread=getSizePerThread(threadSize,fileSize);
System.out.println("共"+threadSize+"个线程,每个线程下载最多:"+sizePerThread+"个字节");
for (int i=0;i<threadSize;i++){
DownloadTaske task=new DownloadTaske(i,fileSize,threadSize,sizePerThread,url,newFilePath);
Thread t=new Thread(task);
t.start();
}
System.out.println("主线程完成");
}
/**
* 获取文件大小
* @param url
* @return
*/
public static long getFileSize(String url){
long fileSize=0;
try {
URL u=new URL(url);
HttpURLConnection con= (HttpURLConnection) u.openConnection();
con.setRequestMethod("HEAD");//请求行:HEAD/xxxHTTP/1.1
fileSize=con.getContentLength();//获取响应的大小
}catch (Exception e){
e.printStackTrace();
}
return fileSize;
}
/**
* 生成文件
* @param url
* @return
*/
public static String getNewFileName(String url){
Date date=new Date();
DateFormat df=new SimpleDateFormat("yyyyMMddHHmmss");
String prefix=df.format(date);
//后缀名
String suffix=url.substring(url.lastIndexOf("."));
return prefix+suffix;
}
/**
* 本地文件保存路径
* @param newFileName
* @return
*/
public static String getNewFilePath(String newFileName){
String userhome="H:\\迅雷下载\\"+ File.separator +newFileName;
return userhome;
}
/**
* 创建新文件
* @param fileSize
* @param newfilePath
* @return
* @throws IOException
*/
public static void createNewFile(long fileSize,String newfilePath) throws IOException {
RandomAccessFile raf=new RandomAccessFile(newfilePath,"rw");
raf.setLength(fileSize);
raf.close();
}
/**
* 计算每个线程要下载的大小
* @param threadSize
* @param fileSize
* @return
*/
public static long getSizePerThread(int threadSize,long fileSize){
return fileSize%threadSize==0?fileSize/threadSize:fileSize/threadSize+1;
}
}
下载任务类文章来源地址https://www.toymoban.com/news/detail-504795.html
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
public class DownloadTaske implements Runnable{
private int i;
private long fileSize;
private int threadSize;
private long sizePerThread;
private String url;
private String newFilePath;
public DownloadTaske(int i, long fileSize, int threadSize, long sizePerThread, String url, String newFilePath) {
this.i = i;
this.fileSize = fileSize;
this.threadSize = threadSize;
this.sizePerThread = sizePerThread;
this.url = url;
this.newFilePath = newFilePath;
}
@Override
public void run() {
long start=i*sizePerThread;
long end=(i+1)*sizePerThread-1;
RandomAccessFile raf=null;
InputStream iis=null;
long total=end-start;
try {
raf=new RandomAccessFile(newFilePath,"rw");
raf.seek(start);
URL urlobj=new URL(url);
HttpURLConnection con= (HttpURLConnection) urlobj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Range","bytes="+start+"-"+end);
con.setConnectTimeout(10*1000);
con.connect();
//开始下载
iis=new BufferedInputStream(con.getInputStream());
byte[] bs=new byte[1024*100];
int length=0;
while ((length=iis.read(bs,0,bs.length))!=-1){
raf.write(bs,0,length);
}
System.out.println("线程:"+i+"完成");
}catch (Exception e){
e.printStackTrace();
}finally {
if (iis!=null){
try {
iis.close();
}catch (Exception e){
e.printStackTrace();
}
}
if (raf!=null){
try {
raf.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
}
}
到了这里,关于JAVA通过HTTP协议下载网络文件的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!