java里面的三种下载方式

第一种:URL方式,这是一种最简单的,只是将下载途径加入到url对象里面,然后用inputstream流将其读出来,再使用fileoutputstream写入到相关的文件途径下面即可。主要代码如下:

URL url=new URL("https://www.duba.com/?f=einfo_liebao");
FileOutputStream fos=new FileOutputStream("D:\\android\\abc\\td.txt");
InputStream is=url.openStream();
int r;
byte []b=new byte[1024];
while((r=is.read(b))!=-1){
fos.write(b,0,r);

}
fos.close();
System.out.println("已经成功下载");


第二种:是一种基于URL方式封装起来的。它不像第一种方式那样只能添加途径到url对象里面,然后只能等到程序运行结束,其中不能添加任何条件。这个可以利用相关的方法了解到相关的错误码,可以决定下载进程,下载速度、多线程等。

package text4;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


public class Download {


public static void main(String[] args) {
// TODO Auto-generated method stub
try {
URL url=new URL("http://sw.bos.baidu.com/sw-search-sp/software/30f44738c65/QQ_8.4.18357.0_setup.exe");
final HttpURLConnection conn=(HttpURLConnection)url.openConnection();
if(conn.getResponseCode()==200){
System.out.println(conn.getContentLengthLong());
final long length=conn.getContentLengthLong();
new Thread(new Runnable() {

@Override
public void run() {
try {
InputStream is=conn.getInputStream();
FileOutputStream fos=new FileOutputStream("D://android//abc//qq.exe");
final File file=new File("D://android//abc//qq.exe");
new Thread(new Runnable() {
public void run() {
while(true){

double len=file.length();
double c=len/length*100;
System.out.printf("已下载%.2f%%\n",c);
if(len==length){
System.out.println("下载成功");
break;
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}
}).start();
byte[]b=new byte[1024*1024];
int len;
while((len=is.read(b))!=-1){
fos.write(b, 0, len);
}
fos.close();
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for(int i=0;i<10;i++){
System.out.println("第"+(i+1)+"次打酱油");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}


}
}).start();
}

} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}


}

第三种:是使用了okhttp jar包写的,这种写法思想是先将网上的东西下载下来存到内存里面,然后一次性写入你想下载的途径里。在文件比较小的时候,这个使用比较方便。但是在文件比较大的时候,一般建议使用第二种方法。减少内存占用


package text4;
import java.io.FileOutputStream;
import java.io.IOException;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


public class Download1 {


public static void main(String[] args) {
// TODO Auto-generated method stub
//创建客户端,(可以看成是浏览器)
OkHttpClient client=new OkHttpClient();
Request request=new Request.Builder().url("http://d.ifengimg.com/mw978_mh598/p2.ifengimg.com/a/2016_26/ab7aa9d12669d60_size82_w434_h653.jpg").build();
try {
Response response=client.newCall(request).execute();
if(response.isSuccessful()){
FileOutputStream fos=new FileOutputStream("D://android//abc//mao.txt");
//response.body().bytes();//得到服务器响应内容的字节数组
fos.write(response.body().bytes());//如果资源大于1M的时候建议使用byteStream()得到流来处理
//先将资源写到内存里面,然后一次型写入文本里面
fos.close();
System.out.println("下载成功");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}


}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Java多线程下载文件可以使用Java并发编程中的concurrent包来实现。一般有两种方式:一种是将网络路径的文件流切割成多块,每个线程下载一小部分,然后写入到文件里面,组成一个文件;另一种是使用线程池,当有多个文件需要下载时,每个线程去下载一个文件即可。以下是一个使用线程池的示例代码: ```java public class DownloadFileWithThreadPool { public void getFileWithThreadPool(String urlLocation, String filePath, int poolLength) throws IOException { ExecutorService threadPool = Executors.newCachedThreadPool(); long len = getContentLength(urlLocation); System.out.println(len); for (int i = 0; i < poolLength; i++) { long start = i * len / poolLength; long end = (i + 1) * len / poolLength - 1; if (i == poolLength - 1) { end = len; } System.out.println(start + "---------------" + end); DownloadWithRange download = new DownloadWithRange(urlLocation, filePath, start, end); threadPool.execute(download); } threadPool.shutdown(); } public static long getContentLength(String urlLocation) throws IOException { URL url = null; if (urlLocation != null) { url = new URL(urlLocation); } HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(5000); conn.setRequestMethod("GET"); long len = conn.getContentLength(); return len; } } ``` 其中,getFileWithThreadPool方法接收三个参数:urlLocation表示文件的网络路径,filePath表示文件下载后保存的本地路径,poolLength表示线程池的大小。getContentLength方法用于获取文件的长度。DownloadWithRange是一个实现了Runnable接口的类,用于下载文件的具体实现。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

tiwolf_li

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值