Now you can Subscribe using RSS

Submit your Email

Tuesday

Android copy files from assets to datafile in Internal Storage.

Vishal Shrestha
Copying files from assets folder to internal storage in Android is not a difficult task. It consists of three parts:

Copying-files-from-assets-folder-to-internal-storage
Assets folder directory structure


How to copy files from assets to Internal Storage Android - 
  1. First make sure the assets folder is in the correct location. The correct location of Assets folder in Android is youappname\app\src\main.
  2. Creating a file in the internal storage where you will write the file that is copied from the assets folder.
  3. Finally copying the file.
Here is the sample code for copying a file called yourdata.extension from the assets folder to the internal storage in a file called yourapp - 
 
        Context context = getApplicationContext();
        String path = Environment.getExternalStorageDirectory()+"/yourapp/";
        File file = new File(path+ "yourdata.extension");
        if (!file.exists()) {
            dir.mkdirs();
            copyFile(context);
        }


                private void copyFile(Context context) {
        AssetManager assetManager = context.getAssets();
        try {
            InputStream in = assetManager.open("eng.traineddata");
            OutputStream out = new FileOutputStream(path+"yourdata.extension");
            byte[] buffer = new byte[1024];
            int read = in.read(buffer);
            while (read != -1) {
                out.write(buffer, 0, read);
                read = in.read(buffer);
               }
            } catch (Exception e) {
            e.getMessage();
          }
        } 


So we've seen that copying files from assets to internal storage is pretty easy in Android, you just have to make sure that the assets folder is in the correct directory. This might be confusing at first as earlier, the location of assets folder was different, but now the location of assests folder is in the main folder of your app, i.e - yourappname\app\src\main. This sums up how to copy files from assets folder to internal storage in Android. If you have any question, feel free to drop them below. Happy coding!

Vishal Shrestha / Author & Founder

A developer by profession, a born Adventurer. I mainly do Android but like to get my hands dirty with web development and a little bit of Python. I would't rather go on a Trek than a party and you can find me having a few rounds with the heavy bag to let out the steam ;)

For Business info : My Portfolio Site.

0 comments:

Post a Comment

Coprights @ 2017 | The Code City by Vishal Shrestha Vishal Shrestha