docAndoid 向目录拷贝文件

来源:互联网 发布:c语言输出单引号 编辑:程序博客网 时间:2024/05/18 00:48

/google

/google/google.htm

/google/google_files/libai11-hp.jpg

/google/google_files/mgyhp_sm.png


1) 测试, 目录打开会报异常,文件打开正常    


    public void copyAssets()   
    {   
   
        final String kkk = "/data/data/com.ziilabs.magicwares/kkk/";
        File folder = new File(kkk);
        if(!folder.exists())   
        {   
            if(!folder.mkdirs())   
            {   
                Log.v("@@@@", "Dir: " + URI_PATH + "     create failed ~~~"); 
            }   
        }
       
       
        try {
            InputStream in = null;
            in = this.getResources().getAssets().open("google/google.htm");
            Log.v("@@@@", "  file :  in =  ###" +  in + "###");
           
             File dataFile = new File(kkk + "google.htm");
             FileOutputStream fos = new FileOutputStream(dataFile);
             byte buff[] = new byte[1024];
               
             do
             {
                 int numread = in.read(buff);
                 if(numread <= 0)
                 {
                     break;
                 }
                 fos.write(buff,0,numread);
             } while(true);
       
             in.close();
             fos.close();
               
            } catch (FileNotFoundException e2) {
                // TODO Auto-generated catch block
                Log.v("@@@@", " write file" +  " FileNotFoundException  ");
                e2.printStackTrace();
            } catch (IOException e2) {
                // TODO Auto-generated catch block
                Log.v("@@@@", " write file" +  " FileNotFoundException  ");
                e2.printStackTrace();
            }
           
       
        try {
            InputStream in = null;
            in = this.getResources().getAssets().open("google/google_files");
            Log.v("@@@@", "  folder :  in =  ###" +  in + "###");
           
           
             File dataFile = new File(kkk + "google_files");
             FileOutputStream fos = new FileOutputStream(dataFile);
             byte buff[] = new byte[1024];
               
             do
             {
                 int numread = in.read(buff);
                 if(numread <= 0)
                 {
                     break;
                 }
                 fos.write(buff,0,numread);
             } while(true);
       
             in.close();
             fos.close();
               
        } catch (FileNotFoundException e4) {
            // TODO Auto-generated catch block
            Log.v("@@@@", " write folder" +  " FileNotFoundException  ");
            e4.printStackTrace();
        } catch (IOException e4) {
            // TODO Auto-generated catch block
            Log.v("@@@@", " write folder " +  " FileNotFoundException  ");
            e4.printStackTrace();
        }
   
    }  


2) 通过异常来判断是文件还是目录,写递归函数,下面事参考的网上的代码

http://www.etongsou.com/soso_detail_1413.htm


    public   void   FindFile(string   dir)                           //参数为指定的目录
    {     
        //在指定目录及子目录下查找文件,在listBox1中列出子目录及文件
        DirectoryInfo Dir = new DirectoryInfo(dir);
        try
        {
            foreach(DirectoryInfo   d   in   Dir.GetDirectories())     //查找子目录   
            {
                FindFile(Dir+d.ToString()+"//");
                listBox1.Items.Add(Dir+d.ToString()+"//");       //listBox1中填加目录名
            }
            foreach(FileInfo   f   in   Dir.GetFiles("*.*"))             //查找文件
            {
                listBox1.Items.Add(Dir+f.ToString());     //listBox1中填加文件名
            }
        }
        catch(Exception   e)
        {
            MessageBox.Show(e.Message);
        }
    }


递归的创建文件夹和拷贝文件java代码: 

    static String WEBPAGE = "/data/data/com.ziilabs.magicwares/webpage/";
    final static String FOLDER = "webpage";
    final static String APP = "/data/data/com.ziilabs.magicwares/";


//把assets目录里面的webpage文件夹拷贝到/data/data/com.ziilabs.magicwares/下

//     assets/webpage/*   --->  //data/data/com.ziilabs.magicwares/webpage/

public void copyAssets() {

        File webpage = new File(WEBPAGE);
       
        webpage.mkdir();
        if (!webpage.exists()) {
            Log.v("copyAssets" , " failed create ! " + webpage);
        }
       
        findFile(FOLDER);
    }
   
    public void findFile (String assDir) {
   
        //get both folder and file name
        String[] files;
        try  
        {  
            files = this.getResources().getAssets().list(assDir);   
        }   
        catch (IOException e1)   
        {   
            return;       
        }
       
        //Log.v(" <findFile> ", "files.length = " + files.length);
       
        for (int i = 0; i < files.length; i++) {
            Log.v(" <findFile> ", "dir:" + assDir + "/" + files[i]);
            String assFile = assDir + "/" + files[i];
            handlerFiles(assFile);
        }
       
    }
   
    public void handlerFiles(String assDir) {   //  
        String filePath = APP + assDir;
        File file = new File(filePath);
       
        //Log.v(" handlerFiles ", " : " + file);
       
        if (!file.exists()) {  // "google.htm"
           
            try {   //file
               
                InputStream  in = this.getResources().getAssets().open(assDir);
                FileOutputStream fos = new FileOutputStream(file);
                byte buff[] = new byte[1024];
               
                do
                {
                    int numread = in.read(buff);
                    if(numread <= 0)
                    {
                        break;
                    }
                    fos.write(buff,0,numread);
                }while(true);
               
                in.close();
                fos.close();
               
            } catch (FileNotFoundException e) {  //   folder
                // TODO Auto-generated catch block
                //Log.v("@@@@", " Folder " + filePath);
                File folder = new File(filePath);
                folder.mkdir();
                findFile(assDir);
   
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        //Log.v(" handlerFiles ", " : " + file + " end /n/n");
        }
    }




用tar来实现关键代码



    static String GUIDE_NAME = "webpage.tar";
    static String URI_PATH = "/data/data/com.ziilabs.magicwares/files/";
    private static final String MODEL3 = URI_PATH + "webpage.tar";
    String cmdStrs1[] = new String[]{"tar", "-xf" , MODEL3 , "-C" , URI_PATH};
    private static final String FILE3 = URI_PATH + "webpage/Google.html";


    public void CmdExec(String[] cmdline) {
        try {
            String line;
            Process p = null;
            if (p != null) {
                p.destroy();
                p = null;
            }
          
            p = Runtime.getRuntime().exec(cmdline);
            BufferedReader input = new BufferedReader(new InputStreamReader(p
                    .getInputStream()));
            line = input.readLine();
            while (line != null) {
                line = input.readLine();
                System.out.println(line);
            }
            input.close();
            p.waitFor();
            int ret = p.exitValue();
            System.out.println(ret);
        } catch (Exception err) {
            err.printStackTrace();
        }
    }
   
    public void loadRes()
    {   
        File folder = new File(URI_PATH);
        if( !folder.exists() ) {
           
            Log.v("@@@@", "Dir: " + URI_PATH + "     not exsit ~~~");
            folder.mkdir();
           
            if( !folder.exists() ) {
                Log.v("@@@@", "Dir: " + URI_PATH + "     create faild ~~~");
            } else {
                Log.v("@@@@", "Dir: " + URI_PATH + "     create suc ~~~");
            }
           
            InputStream in = getResources().openRawResource(R.raw.webpage);
            File file = new File(URI_PATH + GUIDE_NAME);
            try {
                FileOutputStream fos = new FileOutputStream(file);
                byte buff[] = new byte[1024];
               
                do
                {
                    int numread = in.read(buff);
                    if(numread <= 0)
                    {
                        break;
                    }
                    fos.write(buff,0,numread);
                }while(true);
               
                in.close();
                fos.close();
               
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                Log.v("@@@@", "Dir: " + URI_PATH + "   FileNotFoundException  ");
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                Log.v("@@@@", "Dir: " + URI_PATH + GUIDE_NAME + " file IOException");
                e.printStackTrace();
            }
        }     
        else {
            Log.v("@@@@", "Dir: " + URI_PATH + "   aready exsit ~~~");
        }
    }


   int main {

          //do some handle

          loadRes();  
          CmdExec(cmdStrs1);

           ...

          //

   }


3 网上的解压zip的方法,没有测试(下面是转载)

网址: http://gavinju.javaeye.com/blog/100087

Java解压Zip文件

近日,在别的Java论坛上看到有人贴出的Java解压Zip的源码,据说是有问题,小弟昨日小做测试,没有问题.

现在,我贴出经过测试后的源码供大家研究学习:

package com.hand;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class Zip {

 /**
  * @param args
  */
 public static int iCompressLevel;  //压缩比  取值范围为0~9
 public static boolean bOverWrite;  //是否覆盖同名文件 取值范围为True和False
 private static ArrayList allFiles = new ArrayList();
 public static String sErrorMessage;
 public static ArrayList Ectract(String sZipPathFile, String sDestPath){
  ArrayList allFileName = new ArrayList();
  try{
   //先指定压缩档的位置和档名,建立FileInputStream对象
   FileInputStream fins = new FileInputStream(sZipPathFile);
   //将fins传入ZipInputStream中
   ZipInputStream zins = new ZipInputStream(fins);
   ZipEntry ze = null;
   byte ch[] = new byte[256];
   while((ze = zins.getNextEntry()) != null){
    File zfile = new File(sDestPath + ze.getName());
    File fpath = new File(zfile.getParentFile().getPath());
    if(ze.isDirectory()){
     if(!zfile.exists())
      zfile.mkdirs();
     zins.closeEntry();
    }else{
     if(!fpath.exists())
      fpath.mkdirs();
     FileOutputStream fouts = new FileOutputStream(zfile);
     int i;
     allFileName.add(zfile.getAbsolutePath());
     while((i = zins.read(ch)) != -1)
      fouts.write(ch,0,i);
     zins.closeEntry();
     fouts.close();
    }
   }
   fins.close();
   zins.close();
   sErrorMessage = "OK";
  }catch(Exception e){
   System.err.println("Extract error:" + e.getMessage());
   sErrorMessage = e.getMessage();
  }
  allFiles.clear();
  return allFileName;
 }
 
 
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  Zip z = new Zip();
  ArrayList a = new ArrayList();
  a = z.Ectract("c://src.zip", "c://");
  System.out.println(a.size());
 }

}

注: 解压C盘根目录下文件src.zip到C盘根目录.


另:附录一将一个字符串分割为子字符串,然后将结果作为字符串数组返回的有用的Java程序.关于split()方法的使用

package com.hand.tools;

public class SplitDemo {
 
 public static String[] ss = new String[20];
 public SplitDemo(){
  String s = "The test in String start action success";
  //在每个空格字符处进行分解
  ss = s.split(" ");
 }

 /**
  * @param args
  * 将一个字符串分割为子字符串,然后将结果作为字符串数组返回。
  * java.lang.string.split
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  SplitDemo demo = new SplitDemo();
  System.out.println("test the length="+ss.length);
  for(int i=0; i < ss.length; i++){
   System.out.println(ss[i]);
  }
  System.out.println("the last element is : "+ ss[6]);
 }

}

运行返回结果:

test the length=7
The
test
in
String
start
action
success
the last element is : success









原创粉丝点击