现在的位置: 首页 > 综合 > 正文

文件下载(java) android

2013年08月07日 ⁄ 综合 ⁄ 共 1938字 ⁄ 字号 评论关闭
	// /////////////////////////////////下载文件功能如下//////////////////////////////////
	private void DownFile(String urlString)
	{

		/*
		 * 连接到服务器
		 */
		double FileLength = 0;
		double DownedFileLength = 0;
		InputStream inputStream = null;
		URLConnection connection = null;
		OutputStream outputStream = null;

		try
		{
			URL url = new URL(urlString);
			connection = url.openConnection();
			if (connection.getReadTimeout() == 5)
			{
				Log.i("---------->", "当前网络有问题");
			}
			inputStream = connection.getInputStream();

		} catch (MalformedURLException e1)
		{
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		/*
		 * 文件的保存路径和和文件名其中Nobody.mp3是在手机SD卡上要保存的路径,如果不存在则新建
		 */
		String savePAth = Environment.getExternalStorageDirectory()
				+ "/lzmDownload";
		File file1 = new File(savePAth);
		if (!file1.exists())
		{
			file1.mkdir();
		}
		String savePathString = Environment.getExternalStorageDirectory()
				+ "/lzmDownload/" + "test.png";
		File file = new File(savePathString);
		try
		{
			L.l("======================newFile:" + file.createNewFile());
			file.createNewFile();
			L.l("======================newFile:" + file.createNewFile());
		} catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		/*
		 * 向SD卡中写入文件,用Handle传递线程
		 */
		Message message = new Message();
		try
		{
			outputStream = new FileOutputStream(file);
			byte[] buffer = new byte[1024 * 4];
			FileLength = connection.getContentLength();
			L.l("==================FileSize:" + FileLength);
			message.what = 0;
			handler.sendMessage(message);
			while (DownedFileLength < FileLength)
			{
				outputStream.write(buffer);
				DownedFileLength += inputStream.read(buffer);
				i = (int) (((double) DownedFileLength / FileLength) * 100);
				Message message1 = new Message();
				message1.what = 1; // downloading... the file
				handler.sendMessage(message1);

			}
			Message message2 = new Message(); // finish the download
			message2.what = 2;
			handler.sendMessage(message2);
		} catch (FileNotFoundException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	// ///////////////////如上为一个下载类/////////////////////////////////////////////

抱歉!评论已关闭.