Monday 21 April 2014

How to transfer image or copy image from assets to SD card in android

Define 

String secureImagesvoltpath=Environment.getExternalStorageDirectory() + "/Livewallaper";

In On Create
createSecuredirectoryifNotExist("kiritbhayani");
       
        CopyAssets();


Methods

public void  createSecuredirectoryifNotExist(String encrypteddirectoryName) {
       
        File dir = new File(secureImagesvoltpath);
          if(dir.exists() && dir.isDirectory()) {
              System.out.println("Directory exist");
          }
          else{
             
              try{
                  if(dir.mkdirs()) {
                     System.out.println("Directory created");
                  } else {
                     System.out.println("Directory is not created");
                  }
                }catch(Exception e){
                  e.printStackTrace();
                }
           
         }
    }
private void CopyAssets() {
            AssetManager assetManager = getAssets();
            String[] files = null;
            try {
                files = assetManager.list("AssetsFoldername");
            } catch (IOException e) {
                Log.e("tag", e.getMessage());
            }
   
            for(String filename : files) {
                System.out.println("File name => "+filename);
                InputStream in = null;
                OutputStream out = null;
                try {
                  in = assetManager.open("Files/"+filename);   // if files resides inside the "Files" directory itself
                  out = new FileOutputStream(Environment.getExternalStorageDirectory().toString()+"/Livewallaper" +"/" + filename);
                  copyFile(in, out);
                  in.close();
                  in = null;
                  out.flush();
                  out.close();
                  out = null;
                } catch(Exception e) {
                    Log.e("tag", e.getMessage());
                }
            }
        }
        private void copyFile(InputStream in, OutputStream out) throws IOException {
            byte[] buffer = new byte[1024];
            int read;
            while((read = in.read(buffer)) != -1){
              out.write(buffer, 0, read);
            }
        }

No comments:

Post a Comment