跪请各位高手请进

adriftor 2004-04-23 11:01:21
下面函数请求一HTTP服务器(服务端读写数据正常),请求下载某一文件的某段数据,结果在调用时有时正常,有时堵塞。请教各位大侠是怎么回事啊
public byte[] download(long start, long len) throws Exception {
long saveSize = 0l;
URL url = null;
URLConnection httpCon = null;
String strUrl = "http://xxx/"+ "servlet/remotefile?fileName=" + java.net.URLEncoder.encode(fileName) + "&actionName=download¶m1=" + start + "," + len;
url = new URL(strUrl);

//连接
httpCon = url.openConnection();

httpCon.setDoInput(true);
httpCon.setUseCaches(false);


httpCon.connect();
System.out.println("start to read data");

java.io.InputStream in = null;
try {

in = httpCon.getInputStream();
}
catch (Exception e) {
}
if (in == null)
throw new Exception("连接网站失败,请与管理员联系!");
java.io.ByteArrayOutputStream os = new java.io.ByteArrayOutputStream();
java.io.DataInputStream di = new java.io.DataInputStream(new java.io.BufferedInputStream(in));
while (in.available() <=0) {
Thread.sleep(10);
}
System.out.println("download start read start="+start + " len="+len);
while(true) {
byte [] b = new byte[1024];//堵塞处,此语句会导致IOException 异常
int n = di.read(b);
if(n<1)
break;
os.write(b,0,n);
}
System.out.println("download end read start="+start + " len="+len);
di.close();
return os.toByteArray();
}
...全文
70 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
CoolAbu 2004-04-23
  • 打赏
  • 举报
回复
while(true) {
byte [] b = new byte[1024];//堵塞处,此语句会导致IOException 异常
int n = di.read(b);
if(n<1)
break;
os.write(b,0,n);
}

换成下面的试试
byte [] b = new byte[1024];//堵塞处,此语句会导致IOException 异常
int n = di.read(b);
os.write(b,0,n);

还有,可以使用缓冲流来读,这样好一点
OnlyLikeJava 2004-04-23
  • 打赏
  • 举报
回复
有可能是你的数组太小了!
遇到大的文件的时候就会出错,不妨在把数组改的大一些。
bluesmile979 2004-04-23
  • 打赏
  • 举报
回复
while(true) {
byte [] b = new byte[1024];//堵塞处,此语句会导致IOException 异常
int n = di.read(b);
if(n<1)
break;
os.write(b,0,n);
if(n<1024)break;//加这句试试看
}
flyxxxxx 2004-04-23
  • 打赏
  • 举报
回复
信息太少。
升烟 2004-04-23
  • 打赏
  • 举报
回复
os.write(b,0,n);
改称:
buf = new byte[n];
System.arraycopy(b, 0, buf, 0, n);
//然后吧buf,ArrayList链起来,最后把ArrayList转化成一个byte[]
adriftor 2004-04-23
  • 打赏
  • 举报
回复
to CoolAbu(阿卜-Never Stop(★★★★)) :
我已经用了缓冲,不用缓冲也一样。

to OnlyLikeJava(甜咖啡):
增大数组没用,还是堵塞


谢谢各位高手,还有什么原因吗?
adriftor 2004-04-23
  • 打赏
  • 举报
回复
to bluesmile979(笑着) :
if(n<1024)break;会导致信息没读完就返回

to CoolAbu(阿卜-Never Stop(★★★★)) :
不用循环读的话,文件大时次数就太多,这里还有指定读取长度

62,622

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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