版权声明:版权所有@万星明 https://blog.csdn.net/qq_19533277/article/details/83714045
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* @author 万星明
* @version 创建时间:2018年10月26日 上午9:47:40
*/
public class URLconnection下载 {
public static void main(String[] args) throws Exception {
}
//方法一,采用网络读取流加BufferedOutputStream
public static void way1() throws Exception {
//创建url对象
URL url = new URL("https://wenku.baidu.com/browse/downloadrec?doc_id=af07773acbaedd3383c4bb4cf7ec4afe04a1b18b&");
//创建连接对象
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//判断是否连接成功
if(connection.getResponseCode()==HttpURLConnection.HTTP_OK) {
//创建网络读取流
InputStream is = url.openStream();
//创建本地写入流
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("a.pdf"));
//边读取边写入
byte[] b = new byte[1024];
int len = is.read(b);
while(len!=-1) {
bos.write(b,0,len);
len = is.read(b);
}
System.out.println("下载成功");
is.close();
bos.close();
}
}
//方法二,采用网络读取流加内存流ByteArrayOutputStream
//采用ByteArrayOutputStream先将数据写入到内存中,然后再一次性写到目标文件中
public static void way2() throws Exception {
URL url = new URL("https://www.baidu.com/img/bd_logo1.png?where=super");
//创建连接对象
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//判断是否连接成功
if(connection.getResponseCode()==HttpURLConnection.HTTP_OK) {
//创建网络读取流
InputStream is = url.openStream();
//创建本地写入流
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int len = is.read(b);
while(len!=-1) {
baos.write(len);
len = is.read(b);
}
baos.writeTo(new FileOutputStream("a.png"));
System.out.println("下载成功");
is.close();
baos.close();
}
}
}