现在的位置: 首页 > 综合 > 正文

android下载的文件比服务器的文件大的原因与解决方案

2013年11月14日 ⁄ 综合 ⁄ 共 460字 ⁄ 字号 评论关闭

最近学习android时写了一个在web服务器下载文件的程序,程序能够下载成功,但是下载下来发现下载的文件比服务器上的文件大,

后来发现问题出现在往sdcard写入的一段程序:

		 output = new FileOutputStream(file);
		 byte buffer[] = new byte[8*1024];
		 while(input.read(buffer) != -1){
			    output.write(buffer);
			 }
		 output.flush();

上面定义的buffer不一定每次都能在执行 read(buffer) 时填充完整

		 output = new FileOutputStream(file);
		 byte buffer[] = new byte[8*1024];
		 int length = 0;
		 while((length=input.read(buffer)) != -1){
			    output.write(buffer,0,length);
			 }
		 output.flush();

改写后,在调用write方法时指定了每次写的大小必须与每次读到的大小一致,这样问题就解决了

抱歉!评论已关闭.