I currently have the following code which reads a file located on the web and writes it to a file on the phone:
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);
Does anyone know whether it is possible (using the setup above or otherwise) to determine the total number of bytes which are to be read before commencing with the download (in order to publish percentage progress to the user as the download proceeds)?
Advertisement
Answer
use the getContentLength
method of 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);