日期:2014-05-20  浏览次数:20594 次

下载文件的代码,有一点不明白,哪位给点解释,有代码。
HttpConnection   connection   =   (HttpConnection)   Connector.open(url);
connection.setRequestMethod(HttpConnection.GET);
connection.setRequestProperty( "User-Agent ", "Profile/MIDP-2.0   Configuration/CLDC-1.0 ");
connection.setRequestProperty( "Content-Language ", "en-US ");
DataInputStream   dataIn   =   connection.openDataInputStream();
ByteArrayOutputStream   byteout   =   null;
byte   buffer[];
int   length   =   (int)connection.getLength();
if(length!=-1){
buffer   =   new   byte[length];
dataIn.readFully(buffer);
}else{
byteout   =   new   ByteArrayOutputStream();
int   ch;
while((ch   =   dataIn.read())!=-1){
                byteout.write(ch);
}
buffer   =   byteout.toByteArray();
}
dataIn.close();
connection.close();
这里下载分两种情况,一种是dataIn.readFully(buffer);一种是ch   =   dataIn.read();都用后一种不可以吗?为什么要选择前一种呢?是速度上很有优势么(有没有人测试过)?

------解决方案--------------------
对于流媒体的数据来说,int length = (int)connection.getLength(); 返回的就是-1,用读块数据的方法也不合适.反过来也一样.
这个只要知道这么用就行了.