Android中资源文件夹res/raw和assets的使用(续)——分割文件以及合并文件

来源:互联网 发布:高中数学网络教学 编辑:程序博客网 时间:2024/05/22 06:09

上次说到Android中资源文件夹res/raw和assets的使用,但是在读取这两个资源文件夹中的文件时会有一定的限制,即单个文件大小不能超过1M,如果读取超过1M的文件会报"Data exceeds UNCOMPRESS_DATA_MAX (1314625 vs 1048576)"的IOException。

 

解决方法如下(假设我们现在要把一个超过1M的文件在程序启动时拷贝到sdcard中)
1.先把需要拷贝的大文件分割成若干个大小小于1M的小文件(事先写个程序来分隔或者使用一些工具,我这里直接写了个程序),把这些
小文件放在assets文件夹中;

2.在程序启动时我们获取这些小文件的文件名,当然我们得事先规定小文件的命名方式方便我们来获取这些文件名;
3.通过获得的小文件名分别建立输入流来合并成一个大文件,并拷贝到sdcard中。

 

下面是解决方法中需要用到的一些代码,仅供参考,不妨自己写。

分割大文件的方法:

view plain
  1. /** 
  2.  * 指定大小分割文件 
  3.  *  
  4.  * @author zuolongsnail 
  5.  */  
  6. public static void main(String[] args) throws Exception {  
  7.     // 大文件放置的路径  
  8.     String path = "D:/";  
  9.     // 大文件的文件名称  
  10.     String base = "demo";  
  11.     String ext = ".db";  
  12.     // 以每个小文件1024*1024字节即1M的标准来分割  
  13.     int split = 1024 * 1024;  
  14.     byte[] buf = new byte[1024];  
  15.     int num = 1;  
  16.     // 建立输入流  
  17.     File inFile = new File(path + base + ext);  
  18.     FileInputStream fis = new FileInputStream(inFile);  
  19.     while (true) {  
  20.         // 以"demo"+num+".db"方式来命名小文件即分割后为demo1.db,demo2.db,。。。。。。  
  21.         FileOutputStream fos = new FileOutputStream(new File(path + base  
  22.                 + num + ext));  
  23.         for (int i = 0; i < split / buf.length; i++) {  
  24.             int read = fis.read(buf);  
  25.             fos.write(buf, 0, read);  
  26.             // 判断大文件读取是否结束  
  27.             if (read < buf.length) {  
  28.                 fis.close();  
  29.                 fos.close();  
  30.                 return;  
  31.             }  
  32.         }  
  33.         fos.close();  
  34.         num++;  
  35.     }  
  36. }  

获取输入流来合并文件,我们这里以assets文件夹下的文件为例,raw文件夹下如何获取输入流请参考之前的那篇博文。

view plain
  1. /** 
  2.  * 合并文件 
  3.  *  
  4.  * @param c 
  5.  * @param partFileList 小文件名集合 
  6.  * @param dst 目标文件路径 
  7.  * @throws IOException 
  8.  *  
  9.  * @author zuolongsnail 
  10.  */  
  11. private void mergeApkFile(Context c, ArrayList<String> partFileList, String dst) throws IOException {  
  12.     if (!new File(dst).exists()) {  
  13.         OutputStream out = new FileOutputStream(dst);  
  14.         byte[] buffer = new byte[1024];  
  15.         InputStream in;  
  16.         int readLen = 0;  
  17.         for(int i=0;i<partFileList.size();i++){  
  18.             // 获得输入流  
  19.             in = c.getAssets().open(partFileList.get(i));  
  20.             while((readLen = in.read(buffer)) != -1){  
  21.                 out.write(buffer, 0, readLen);  
  22.             }  
  23.             out.flush();  
  24.             in.close();  
  25.         }  
  26.         // 把所有小文件都进行写操作后才关闭输出流,这样就会合并为一个文件了  
  27.         out.close();  
  28.     }  
  29. }  

这样就OK了,大文件已经拷贝到你需要的路径中了。 


http://blog.csdn.net/zuolongsnail/article/details/6459580

原创粉丝点击