Android File(二) File下载以及解压

   上篇文章,我们了解了有关File的一些常用方法,如果你还不了解,请看 Android File(一) 存储以及File操作介绍。我们 项目开发中可能会有这样的需求,“app刚启动的时候,可能需要从服务器把有的资源先下载到本地,然后才在app中加载、显示”,那么接下来我们就实现这样的功能。(从网络下载一个压缩包以及解压该文件

一.新建项目。这个就不多说了!

二.实现。

  1.文件工具类。

    上篇文件我整理了一个文件工具类-FileUtils,FileUtils下载地址。这里在简单介绍一下,在该实现中用到的方法:

1.1 SD卡是否可用,

 /**
	 * 当SD卡存在或者SD卡不可被移除才可使用
	 * 
	 * @return
	 */
	public static boolean isSDCardMounted() {
		return Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)|| !Environment.isExternalStorageRemovable();
	}
1.2设置文件的下载路径,

/**
	 * 设置文件的下载路径
	 * 
	 * @param context
	 * @param uniqueName
	 * @return
	 */
	public static String getDiskCachePath(Context context, String uniqueName) {
		String cachePath;
		if (isSDCardMounted()) {
			cachePath = context.getExternalFilesDir("").getPath();
		} else {
			cachePath = context.getFilesDir().getPath();
		}
		return cachePath + File.separator + uniqueName;
	}
1.3 删除文件或文件夹,

/**
	 * 删除文件或文件夹
	 * 
	 * @param path
	 *            文件或文件夹的路径
	 */
	public static void deleteFile(String path) {
		deleteFile(new File(path));
	}

	/**
	 * 删除文件或文件夹
	 * 
	 * @param file
	 *            文件或文件夹
	 */
	public static void deleteFile(File file) {
		if (!file.exists()) {
			Log.d("The file to be deleted does not exist! File's path is: ",
					file.getPath());
		} else {
			deleteFileRecursively(file);
		}
	}

	/**
	 * 删除文件或文件夹
	 * 
	 * @param file
	 *            文件或文件夹
	 */
	private static void deleteFileRecursively(File file) {
		if (file.isDirectory()) {
			for (String fileName : file.list()) {
				File item = new File(file, fileName);
				if (item.isDirectory()) {
					deleteFileRecursively(item);
				} else {
					if (!item.delete()) {
						Log.d("Failed in recursively deleting a file, file's path is: ",
								item.getPath());
					}
				}
			}
			if (!file.delete()) {
				Log.d("Failed in recursively deleting a directory, directories' path is: ",
						file.getPath());
			}
		} else {
			if (!file.delete()) {
				Log.d("Failed in deleting this file, its path is: ",
						file.getPath());
			}
		}
	}
1.4解压缩一个文件,

/**
     * 解压缩一个文件
     * 
     * @param zipFile 压缩文件
     * @param folderPath 解压缩的目标目录
     * @throws IOException 当解压缩过程出错时抛出
     */
    public static void upZipFile(File zipFile, String folderPath) throws ZipException, IOException {
        File desDir = new File(folderPath);
        if (!desDir.exists()) {
            desDir.mkdirs();
        }
        ZipFile zf = new ZipFile(zipFile);
        for (Enumeration<?> entries = zf.entries(); entries.hasMoreElements();) {
            ZipEntry entry = ((ZipEntry) entries.nextElement());
            InputStream in = zf.getInputStream(entry);
            String str = folderPath + File.separator + entry.getName();
            str = new String(str.getBytes("8859_1"), "GB2312");
            File desFile = new File(str);
            if (!desFile.exists()) {
                File fileParentDir = desFile.getParentFile();
                if (!fileParentDir.exists()) {
                    fileParentDir.mkdirs();
                }
                desFile.createNewFile();
            }
            OutputStream out = new FileOutputStream(desFile);
            byte buffer[] = new byte[BUFF_SIZE];
            int realLength;
            while ((realLength = in.read(buffer)) > 0) {
                out.write(buffer, 0, realLength);
            }
            in.close();
            out.close();
        }
    }</span>
以上几个方法就够用了,当然还有其他的方法,我们暂时就不介绍了!大家可以下载demo查看!

2.下载文件方法。

    就简单的实现了下载功能,你觉得不好,当然可以修改哦!下面看看具体实现,

/**
	 * 下载压缩包文件
	 * @param fileUrl
	 * @param dir
	 * @param fileName
	 * @return
	 */
	public static String downFile(String fileUrl, String dirPath, String zipFilePath) {
		File dirFile = new File(dirPath);// 目录
		if (!dirFile.exists()) {
			dirFile.mkdir();
		}
		File file = new File(zipFilePath);// 保存文件
		if (file.exists()) {
			file.delete();
		}
		try {
			// 构造URL
			URL url = new URL(fileUrl);
			// 打开连接
			URLConnection con = url.openConnection();
			con.setConnectTimeout(10 * 1000);
			con.setReadTimeout(10 * 1000);
			// 获得文件的长度
			int contentLength = con.getContentLength();
			System.out.println("长度 :" + contentLength);
			// 输入流
			InputStream is = con.getInputStream();
			// 1K的数据缓冲
			byte[] bs = new byte[1024];
			// 读取到的数据长度
			int len;
			// 输出的文件流
			OutputStream os = new FileOutputStream(file);
			// 开始读取
			while ((len = is.read(bs)) != -1) {
				os.write(bs, 0, len);
			}
			// 完毕,关闭所有链接
			os.close();
			is.close();
			Log.e("tag", "zipFilePath---------------:" + zipFilePath);
			return zipFilePath;
		} catch (IOException e) {
			Log.e("tag", e.toString() + "图片下载及保存时出现异常 !");
		}
		return null;
	}
这个很简单吧!不用再多解释了!

3.使用异步任务去完成下载功能以及解压功能

    具体实现如下,

/**
	 * 下载资源包
	 */
	public class ImagesDownLoaderTask extends AsyncTask<Void, Integer, Boolean> {
		private String url;
		private String dir;
		private String zipName;

		public ImagesDownLoaderTask(String url, String dir, String zipName) {
			super();
			this.url = url;
			this.dir = dir;
			this.zipName= zipName;
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
		}

		@Override
		protected Boolean doInBackground(Void... params) {
			// TODO Auto-generated method stub
			// 下载文件
			String path = downFile(url, dir, dir
					+ File.separator + zipName);
			if (!TextUtils.isEmpty(path)) {
				File zipFile = new File(path);
				String outPath = dir + File.separator + unZipPath;
				try {
					// 解压文件
					FileUtils.upZipFile(zipFile, outPath);
					return true;
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			return false;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			getImagesPath();
		}
	}
下载完成后,去解压缩,解压缩后,去获取图片的本地路径。getImagesPath()方法是获取图片的本地路径,实现如下,

/**
	 * 获取图片路径
	 */
	private void getImagesPath() {
		// 遍历目录
		String path = dir + File.separator + unZipPath;
		File zipFile = new File(path);
		mList.clear();
		if (zipFile.isDirectory()) {
			File files[] = zipFile.listFiles();
			for (int i = 0; i < files.length; i++) {
				String filePath = files[i].getPath();
				mList.add(filePath);
			}
		}
	}
经过以上几步,我们就大抵可以实现简单的文件下载以及解压缩。

PS:在AndroidManifest.xml加入以下权限

<uses-permission android:name="android.permission.INTERNET"/>
     <!-- 在SD卡中创建与删除文件权限 -->
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
    <!-- 向SD卡写入数据权限 -->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.WRITE_SETTINGS"/>
三.总结。

      看过这篇文章,就很容易的实现文章开头所说的功能了! 代码的实现都比较简单,所以就不做过多的解释了!

     推荐2篇文章 Android File(一) 存储以及File操作介绍Android View(一)-View坐标以及方法说明。

PS: demo工程下载地址!

       demo工程中,由于需要提供文件的下载路径,我暂时没有外网的公共资源,所以,大家在下载工程后,只需要把文件的下载路径该为自己的就可以了。



    




   




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值