能不能用JAVA编写一个程序从网上下载一张图片呢?求完整程序!
3个回答
展开全部
package com.capinfotech.net;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class ImageRequest {
public static void main(String[] args) throws IOException {
URL url = new URL("https://gss0.baidu.com/7Po3dSag_xI4khGko9WTAnF6hhy/album/w%3D2048/sign=1bb39918cdbf6c81f7372be88806b035/9345d688d43f879423f3355ed31b0ef41bd53ab5.jpg");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
InputStream inputStream = conn.getInputStream(); //通过输入流获得图片数据
byte[] getData = readInputStream(inputStream); //获得图片的二进制数据
File imageFile = new File("tupian.jpg");
FileOutputStream fos = new FileOutputStream(imageFile);
fos.write(getData);
fos.close();
System.out.println(" read picture success");
}
public static byte[] readInputStream(InputStream inputStream) throws IOException {
byte[] buffer = new byte[1024];
int len = 0;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while((len = inputStream.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
bos.close();
return bos.toByteArray();
}
}
展开全部
private static void download(String picUrl, String pathName) throws Exception {
URL url = new URL(picUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout((int) TimeUnit.SECONDS.toMillis(30L));
try(InputStream inputStream = connection.getInputStream();
FileOutputStream outputStream = new FileOutputStream(new File(pathName))) {
byte[] buffer = new byte[1024];
int len;
while((len = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, len);
}
}
}
URL url = new URL(picUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout((int) TimeUnit.SECONDS.toMillis(30L));
try(InputStream inputStream = connection.getInputStream();
FileOutputStream outputStream = new FileOutputStream(new File(pathName))) {
byte[] buffer = new byte[1024];
int len;
while((len = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, len);
}
}
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
能准确一点描述你的问题吗?
更多追问追答
追问
就是利用URL和io流实现从网上下载一张图片并保存到电脑中。求指教
追答
你是想做下载功能吧?
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询