关于将网络上的图片下载保存到本地的效率对比
Android里面将图片保存到本地,到网络上搜索了一下,方法都差不多,大同小异,把输入流转换成输出流的过程而已。最近工作闲,特把其中的两个方法对比一下,看他们的效率如何(找javaSE里面测试的):第一种方法:
public static void main(String[] args) {String url = "http://pic.yesky.com/imagelist/09/01/11277904_7147.jpg";Long time1 = System.currentTimeMillis();Long time2 = 0L;try {FileOutputStream fos = new FileOutputStream( "c:\\tmp.jpg ");InputStream is = new URL(url).openStream();time2 = System.currentTimeMillis();int data = is.read(); while(data!=-1){ fos.write(data); data=is.read(); } is.close();fos.close();} catch (IOException e) {e.printStackTrace();} Long time3 = System.currentTimeMillis();System.out.println("网络读取流的时间:" + (time2 - time1) + " 把输入流保存成文件的时间:"+ (time3 - time2));}
第二种方法:中间用buffer做缓存
public static void main(String[] args){String url = "http://pic.yesky.com/imagelist/09/01/11277904_7147.jpg";Long time1 = System.currentTimeMillis();Long time2 = 0L;try {int bytesum=0; int byteread=0;FileOutputStream fos = new FileOutputStream( "c:\\tmp2.jpg ");InputStream is = new URL(url).openStream();time2 = System.currentTimeMillis();byte[] buffer =new byte; while ((byteread=is.read(buffer))!=-1) { bytesum+=byteread; // System.out.println(bytesum); fos.write(buffer,0,byteread); } is.close();fos.close();} catch (IOException e) {e.printStackTrace();} Long time3 = System.currentTimeMillis();System.out.println("网络读取流的时间:" + (time2 - time1) + " 把输入流保存成文件的时间:"+ (time3 - time2));}
每个方法测试了三次,结果如下:
第一种方法:
网络读取流的时间:453 把输入流保存成文件的时间:766
网络读取流的时间:344 把输入流保存成文件的时间:344
网络读取流的时间:297 把输入流保存成文件的时间:281
第二种方法:
网络读取流的时间:312 把输入流保存成文件的时间:282
网络读取流的时间:3484 把输入流保存成文件的时间:906
网络读取流的时间:828 把输入流保存成文件的时间:1250
第一种方法,发现效率高过第二种方法,而且第一种方法写法简洁的多。建议用第一种方法。
其实在android里面,不建议直接把网络图片原样写人sd里面,毕竟手机的sd空间是有限的。最常用的方法是把网络图片压缩成jpg格式保存:
byte[] data = readInputStream(new URL(url).openStream());Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0,data.length);bitmap.compress(CompressFormat.JPEG, 100, new FileOutputStream(file));
readInputStream()方法的代码:(把输入流转换成比特流)
public static byte[] readInputStream(InputStream inStream) throws Exception{ ByteArrayOutputStream outSteam = new ByteArrayOutputStream(); byte[] buffer = new byte; int len = 0; while( (len = inStream.read(buffer)) != -1 ){ outSteam.write(buffer, 0, len); } outSteam.close(); inStream.close(); return outSteam.toByteArray();}
页:
[1]