分享

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

 Babylly 2011-12-19

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


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

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


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

分割大文件的方法:


view plaincopy to clipboardprint?

  • /**
  • * 指定大小分割文件
  • *
  • * @author zuolongsnail
  • */
  • public
    static
    void main(String[] args) throws Exception {  
  •     // 大文件放置的路径
  •     String path = "D:/";  
  •     // 大文件的文件名称
  •     String base = "demo";  
  •     String ext = ".db";  
  •     // 以每个小文件1024*1024字节即1M的标准来分割
  •     int split = 1024 * 1024;  
  •     byte[] buf = new
    byte[1024];  
  •     int num = 1;  
  •     // 建立输入流
  •     File inFile = new File(path + base + ext);  
  •     FileInputStream fis = new FileInputStream(inFile);  
  •     while (true) {  
  •         // 以"demo"+num+".db"方式来命名小文件即分割后为demo1.db,demo2.db,。。。。。。
  •         FileOutputStream fos = new FileOutputStream(new File(path + base  
  •                 + num + ext));  
  •         for (int i = 0; i < split / buf.length; i++) {  
  •             int read = fis.read(buf);  
  •             fos.write(buf, 0, read);  
  •             // 判断大文件读取是否结束
  •             if (read < buf.length) {  
  •                 fis.close();  
  •                 fos.close();  
  •                 return;  
  •             }  
  •         }  
  •         fos.close();  
  •         num++;  
  •     }  
  • }  


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


view plaincopy to clipboardprint?

  • /**
  • * 合并文件
  • *
  • * @param c
  • * @param partFileList 小文件名集合
  • * @param dst 目标文件路径
  • * @throws IOException
  • *
  • * @author zuolongsnail
  • */
  • private
    void mergeApkFile(Context c, ArrayList<String> partFileList, String dst) throws IOException {  
  •     if (!new File(dst).exists()) {  
  •         OutputStream out = new FileOutputStream(dst);  
  •         byte[] buffer = new
    byte[1024];  
  •         InputStream in;  
  •         int readLen = 0;  
  •         for(int i=0;i<partFileList.size();i++){  
  •             // 获得输入流
  •             in = c.getAssets().open(partFileList.get(i));  
  •             while((readLen = in.read(buffer)) != -1){  
  •                 out.write(buffer, 0, readLen);  
  •             }  
  •             out.flush();  
  •             in.close();  
  •         }  
  •         // 把所有小文件都进行写操作后才关闭输出流,这样就会合并为一个文件了
  •         out.close();  
  •     }  
  • }  


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


    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多