« Back

Downloading a File

Downloading a file is a seemingly mundane task that most people do everyday on their computers in some way or another. This process is a little bit more than clicking on a link, however, because in the background a stream has to be initialized, the image or file has to be transferred from the remote server to the client's computer, and then a file location has to be designated locally for the downloaded file to be stored in. This is the same process that must be taken for a file to be downloaded on a tablet or other mobile device as well, and below I will detail how to programmatically download a file by opening a URL stream and storing the file locally in your application's file directory.

I want to start off by saying that there are multiple ways to download files programmatically in Android and the way I will be detailing is by no means the only one. Possibly, in a future posts, I will detail some of the alternatives to the way I am about to describe. However, the way that I am about to describe is one of the more popular methods and is detailed in other Android how-to blogs around the Internet. The function that you will end up with passes in 3 variables, a URL that is the URL of the file the user wishes to download, a file name that is the chosen file name of the downloaded file in the local file system, and an Android Context variable which should be the application's Context so that the function can access the application's local file's directory.

The process for downloading a file isn't actually that long and consists of 3 main parts. First, various streams need to be opened. This includes an input stream from the URL, a ByteArrayOutputStream to store the downloaded bytes in, and an output stream to the local file. Second, the file will need to be downloaded, byte by byte, into the ByteArrayOutputStream. To shorten this process, a byte array can be used to download chunks of the file at a time. The size of the byte array I specify below is 1024 bytes, or 1 kilobyte, but this can obviously be changed to really any number depending on preference. Finally, the third step is to write the contents of the ByteArrayOutputStream to the file's output stream and then close the streams upon completion. This will give you a complete file stored in the application's local file directory. The complete function is given below:

 1private Boolean downloadFile(String urlPath, String filename, Context mContext) {
 2        Boolean downloadSucceeded=true;
 3       
 4    try {
 5        URL url = new URL(urlPath);
 6        URLConnection urlConn = url.openConnection();
 7        BufferedInputStream bis = new BufferedInputStream(urlConn.getInputStream());
 8        ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
 9        FileOutputStream fos = mContext.openFileOutput(filename, MODE_PRIVATE);
10       
11        int bufferSize = 1024;
12        byte[] buffer=new byte[bufferSize];
13        int len = 0;
14        while ((len = bis.read(buffer)) != -1) {
15            byteBuffer.write(buffer, 0, len);
16        }
17       
18        fos.write(byteBuffer.toByteArray());
19        byteBuffer.close();
20        fos.close();
21    } catch (Exception e) {
22        downloadSucceeded=false;
23    }
24   
25    return downloadSucceeded;
26}

As you can see, most of the code is surrounded by a try/catch block, as there are a few different lines of code in this function that throw exceptions. By surrounding the whole function in a try/catch and using a boolean value as shown, I guarantee that if the download fails for any reason, the returned value showing the success of the download will be false.
Comments