我使用以下代码从URL下载文件:
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
URL url = new URL(address);
Log.i("URL:",address);
URLConnection connection = url.openConnection();
connection.setReadTimeout(timeout);
connection.setConnectTimeout(sockettimeout);
int filesize = connection.getContentLength();
InputStream inputStream = connection.getInputStream();
OutputStream outputStream =new FileOutputStream(path);
byte[] buffer = new byte[2*1024];
int length = 0 ;
downloadedSize = 0;
while((length = inputStream.read(buffer))>0){
outputStream.write(buffer,0,length);
downloadedSize += length;
Log.i("downloaded Size",""+downloadedSize);
listener.onDownloadPercentListener((downloadedSize*100)/filesize);
if(downlaodedSize == filesize){
listener.onDownloadCompleteListener();
}
}
}
});
thread.start();
虽然我的文件已完全下载,但downloadedSize 字段的值始终为零,并且无法执行监听器。
另一个问题是为什么我不能将downloadedSize变量用作本地变量,并且它在 while循环中没有可见性?