文件下载(java) android

	// /下载文件功能如下//
	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();
		}
	}

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值