我目前有以下代码,它读取位于网络上的文件并将其写入手机上的文件:
InputStream inputStream = new URL(sourceFileWebAddress).openStream();
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
FileOutputStream fileOutputStream = new FileOutputStream(targetFile);
int count;
byte buffer[] = new byte[1024];
while ((count = bufferedInputStream.read(buffer, 0, buffer.length)) != -1)
fileOutputStream.write(buffer, 0, count);
有没有人知道是否有可能(使用上面的设置或其他方式)确定在开始下载之前要读取的总字节数(为了在下载过程中向用户发布百分比进度) ?
答案 0 :(得分:8)
使用getContentLength
URLConnection
方法
URL url = new URL(sourceFileWebAddress);
URLConnection connection = url.openConnection();
connection.connect();
int fileLenth = connection.getContentLength();
InputStream inputStream = url.openStream();
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
答案 1 :(得分:3)
URLConnection connection = new URL(sourceFileWebAddress).openStream();
InputStream stream = connection.getInputStream();
System.out.println("total size: "+connection.getContentLength();//size
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
FileOutputStream fileOutputStream = new FileOutputStream(targetFile);
int count;
byte buffer[] = new byte[1024];
while ((count = bufferedInputStream.read(buffer, 0, buffer.length)) != -1)
fileOutputStream.write(buffer, 0, count);
答案 2 :(得分:3)
要确定在开始下载之前要读取的字节总数,一种方法是仅通过发送来获取响应标头 HTTP HEAD 请求如下:
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
public class SimpleHTTPRequest {
public static void main(String[] args) {
HttpURLConnection connection = null;
URL serverAddress = null;
try {
String sourceFileWebAddress = "http://localhost:8080/mycontents";
serverAddress = new URL(sourceFileWebAddress);
//set up out communications stuff
connection = null;
//Set up the initial connection
connection = (HttpURLConnection)serverAddress.openConnection();
//HEAD request will make sure that the contents are not downloaded.
connection.setRequestMethod("HEAD");
connection.connect();
System.out.println("========"+connection.getContentLength());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally
{
//close the connection, set all objects to null
connection.disconnect();
connection = null;
}
}
}
这将打印要下载的内容的大小而不实际下载内容。
答案 3 :(得分:2)
您可以向服务器发送请求以返回文件大小。在进度条中使用该文件大小并启动下载。这些是两个单独的请求,但您可以将它们捆绑在同一个asyc任务中。
因此,您首先获取fielszie,拨打progressUpdate
来设置进度条的值,然后定期调用progressUpdate()
继续下载,以更改进度条的状态。
答案 4 :(得分:1)
getContentLength
的方法URLConnection
应该为您提供要下载的文件的大小。从这里你可以随意绘制你的ProgressBar,更新它(在onProgressUpdate中,假设你在AsyncTask中这样做。你是,对吗?)每当你的fileOutputStream处理新数据时。
如果服务器没有给你getContentLength中的值(在大多数情况下为-1,但至少检查它是否小于或等于零),只需使ProgressBar不确定。