下载远程apk文件出错,求指教

wensefu 2011-07-08 08:47:51
下载的代码如下,
这是一段测试代码,下载到本地的APK文件老是损坏的。直接输地址到浏览器下载下来的则是完整的。我觉得网络的不稳定性是一个因素,但是肯定是可以通过改进代码排除网络因素造成的影响的。求大侠指教!

public static void main(String[] args) {
InputStream is = null;
HttpURLConnection conn=null;
try {
URL url = new URL("http://www.dubblogs.cc:8751/Android/Test/Apk/EX04_14.apk");
conn = (HttpURLConnection) url.openConnection();
conn.connect();
is = conn.getInputStream();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
FileOutputStream fos = null;
BufferedInputStream bis = null;
try {
fos = new FileOutputStream("e:/test4.apk");
byte[] buf = new byte[1024];
bis = new BufferedInputStream(is);
while (bis.read(buf,0,1024) != -1) {
fos.write(buf);
System.out.println(buf);
}
fos.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if (fos != null)
fos.close();
if (bis != null)
bis.close();
if (is != null)
is.close();
conn.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
...全文
208 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
lizhengjun2010 2011-07-20
  • 打赏
  • 举报
回复
while (bis.read(buf,0,1024) != -1) {
fos.write(buf);
System.out.println(buf);
}


read每次读取1024,返回值为实际读取的大小
写入流时必须写入实际大小
fos.write(buf,o,size);
sciolist 2011-07-14
  • 打赏
  • 举报
回复
路过~
雨松MOMO 2011-07-12
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 wensefu 的回复:]

Java code

int size = -1;
while ((size = bis.read(buf)) != -1) {
fos.write(buf, 0, size);
Log.e(TAG, buf + ":buf");
}


这样就好了
[/Quote]

正解!!
passself 2011-07-09
  • 打赏
  • 举报
回复
哦,你原来的代码是每次只是下载1M
wensefu 2011-07-09
  • 打赏
  • 举报
回复

int size = -1;
while ((size = bis.read(buf)) != -1) {
fos.write(buf, 0, size);
Log.e(TAG, buf + ":buf");
}

这样就好了
qiying1988 2011-07-09
  • 打赏
  • 举报
回复
什么原因? 测试你的代码,保存在模拟器上,是可以的。
wensefu 2011-07-09
  • 打赏
  • 举报
回复
搞定了。
passself 2011-07-08
  • 打赏
  • 举报
回复
可能是因为你的缓冲区,太大了,你设小一些

80,352

社区成员

发帖
与我相关
我的任务
社区描述
移动平台 Android
androidandroid-studioandroidx 技术论坛(原bbs)
社区管理员
  • Android
  • yechaoa
  • 失落夏天
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧