Save file to in storage

By
Save file to in storage

When we developed image related functionality that time we need to Save files on android external storage at particular location in mobile. That time we need to create one specific folder, this folder save the our file or images in this location. Let’s see how it possible,

In this tutorial, any Image url save in side android external storage at specific location.

Write given permission in side AndroidManifest.xml.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="come.savedaspecificlocation">

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <uses-permission android:name="android.permission.INTERNET" />

    <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme">

        <activity android:name=".MainActivity">

            <intent-filter>

                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Now create one layout file, called as activity_main.xml
In this layout file, contains one button, this button is used to save file on Android external storage at given location. We can find file from redirecting manually go to the external storage in our mobile or device.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:orientation="vertical" tools:context=".MainActivity">

    <TextView android:id="@+id/tvImageLocation" android:layout_width="match_parent" android:layout_height="wrap_content" />

    <Button android:id="@+id/btnClcikForSave" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:text="@string/click_for_save" />

</LinearLayout>

Now Create one Function called as saveImage() in side theMainActivity.java

  public void saveImage(Context mContext, Bitmap bitmapImage) {

        File sampleDir = new File(Environment.getExternalStorageDirectory() + "/" + "ApplicationName");

        TextView tvImageLocation = (TextView) findViewById(R.id.tvImageLocation);
        tvImageLocation.setText("Image Store At : " + sampleDir);

        if (!sampleDir.exists()) {
            createpathForImage(mContext, bitmapImage, sampleDir);
        } else {
            createpathForImage(mContext, bitmapImage, sampleDir);
        }
    }

Here, sampleDir is full path of your file storage. if yo want to save your file that file located on sampleDir location. While “ApplicationName” specified name that you want to create folder.
Now create one more function createpathForImage() this function create Image or file name and store at given location.

 private void createpathForImage(Context mContext, Bitmap bitmapImage, File sampleDir) {
        try {
            File fileNamePath = File.createTempFile(String.valueOf(System.currentTimeMillis()), ".png", sampleDir);

            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(fileNamePath);
                // Use the compress method on the BitMap object to write image to the OutputStream
                bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        } catch (IOException e) {
            return;
        }
    }

Now, We need to convert our image url to bitmap image.

This function is used to create bitmap image from the given url. so we need to write one more function that are use to convert URL to Bitmap.
Now create one function name is, convertUrlTo_Bitmap

 private Bitmap convertUrlTo_Bitmap(String src) {
        URL url = null;
        try {
            url = new URL(src);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        Bitmap image = null;
        try {
            image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return image;
    }

At the end our  “MainActivity.java”  look like this,

public class MainActivity extends AppCompatActivity {

    Bitmap bitmap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button btnClcikForSave = (Button) findViewById(R.id.btnClcikForSave);

        btnClcikForSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Build.VERSION.SDK_INT &amp;gt;= Build.VERSION_CODES.M) {
                    if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                        Bitmap bitmap = null;
                        bitmap = convertUrlTo_Bitmap("https://cdn.pixabay.com/photo/2015/11/16/14/43/cat-1045782_960_720.jpg");


                            saveImage(MainActivity.this, bitmap);
                    } else {
                        ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 111);
                    }
                } else {
                    saveImage(MainActivity.this, bitmap);
                }
            }
        });

    }

    public void saveImage(Context mContext, Bitmap bitmapImage) {

        File sampleDir = new File(Environment.getExternalStorageDirectory() + "/" + "ApplicationName");

        TextView tvImageLocation = (TextView) findViewById(R.id.tvImageLocation);
        tvImageLocation.setText("Image Store At : " + sampleDir);

        if (!sampleDir.exists()) {
            createpathForImage(mContext, bitmapImage, sampleDir);
        } else {
            createpathForImage(mContext, bitmapImage, sampleDir);
        }
    }

    private void createpathForImage(Context mContext, Bitmap bitmapImage, File sampleDir) {
        try {
            File fileNamePath = File.createTempFile(String.valueOf(System.currentTimeMillis()), ".png", sampleDir);

            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(fileNamePath);
                // Use the compress method on the BitMap object to write image to the OutputStream
                bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        } catch (IOException e) {
            return;
        }
    }

    private Bitmap convertUrlTo_Bitmap(String src) {
        URL url = null;
        try {
            url = new URL(src);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        Bitmap image = null;
        try {
            image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return image;
    }

 @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (grantResults.length == 0 || grantResults == null) {
            /*If result is null*/
        } else if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            /*If We accept permission*/
        } else if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
            /*If We Decline permission*/
        }
    }
}

Latest Blog