IO流中从网上下载图片:
public class Demo{
public static void testDownLoad(){
BufferedInputStream bis =null;
BufferedOutputStream bos=null;
String HTTP_URL=“ ”; //图片地址
try {
int contentLength = getConnection(HTTP_URL).getContentLength();
System.out.println("文件的大小是:"+contentLength);
if (contentLength>32) {
InputStream is= getConnection(HTTP_URL).getInputStream();
bis = new BufferedInputStream(is);
FileOutputStream fos = new FileOutputStream(" ");
bos= new BufferedOutputStream(fos);
int b = 0; byte[] byArr = new byte[1024];
while((b= bis.read(byArr))!=-1){
bos.write(byArr, 0, b);
} System.out.println("下载的文件的大小是------:"+contentLength);
}
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
if(bis !=null){ bis.close();
} if(bos !=null){ bos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static HttpURLConnection getConnection(String httpUrl) throws
Exception {
URL url = new URL(httpUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type", "application/octet-stream");
connection.setDoOutput(true); connection.setDoInput(true);
connection.setRequestProperty("Connection", "Keep-Alive");
connection.connect(); return connection;
}
public static void main(String[] args) {
testDownLoad();
}
}