Dot Product Software Weblog
Programming Insights
Categories:

Archives:
Meta:
June 2026
S M T W T F S
« Jun    
 123456
78910111213
14151617181920
21222324252627
282930  
06/12/13
Download File With Android
Filed under: General
Posted by: Lou Rebimbas @ 3:08 am

Hello,
Someone had asked about downloading a file from a URL onto an android device.
I’ve excluded the imports but you should be able to find the necessary packages without too much trouble.
I originally came up with this function to download bitmaps to load into an app, but it works just as well for any file type.

public void downloadFile(String url){
		InputStream input = null;
		try{
			//Get the stream to the file on the web
			input = new BufferedInputStream(new URL(url).openStream());
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			//Read the data coming in from the stream
			byte[] data = new byte[1024];
			int x = 0;
			while((x = input.read(data,0,1024))>0){
				baos.write(data, 0, x);
			}
			//convert data to a byte array
			byte [] ar = baos.toByteArray();
			//Create a local file
			File newFile = new File(\"/path/to/save/to/music.mp3\");
			FileOutputStream fos = new FileOutputStream(newFile);
			fos.write(ar);
			fos.flush();
			fos.close();
	
			input.close();
			baos.close();
		} catch(IOException iex){
			iex.printStackTrace();
		}
	}

Leave a Reply