下载网络文件

通过url,下载网络文件,图片或者十几兆的视频都可以,其他更大的没试过


public void download()
		{
			URL url;
			try {
				url = new URL("http://XXXXXXXXXXXX/tt.flv");
				
				HttpURLConnection connection = null;
				try {
					connection = (HttpURLConnection)url.openConnection();
					if(connection.getResponseCode() == HttpURLConnection.HTTP_OK){
						InputStream ins = connection.getInputStream();
						File file = new File(tempPath);
						if(file.exists())
						{
							file.delete();
							file.createNewFile();
						}else
						{
							file.createNewFile();
						}
						FileOutputStream out = new FileOutputStream(file);
						byte[] buffer = new byte[256];
						int length = -1;
						while((length=ins.read(buffer)) != -1){
							out.write(buffer, 0, length);
						}
						out.flush();
						ins.close();ins = null;
						out.close();out = null;	
					}					//结束
				} 
				catch (IOException e) 
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}								
				//释放资源
				if(connection != null)
				{
					connection.disconnect();
					connection = null;
				}				
				url = null;
			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}



你可能感兴趣的:(下载网络文件)