MobileAndroidWorking with Files and the File System in Android Apps

Working with Files and the File System in Android Apps

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

Introduction

Most applications have a need to work with files and, in this article, we will cover the basics of file management and have a simple demo.

Basics

Like other modern operating systems, Android has a disk-based file system. There are two storage areas: internal and external. Internal storage refers to the built-in, non-volatile memory. Devices also can come with removable memory (like a SD card), which is referred to as external storage.

The internal storage is also occasionally referred to as permanent storage. Files saved in internal storage are accessible only to your app by default.

External storage can be removed at any time and files saved here can be accessible to everyone.

Applications can allow themselves to be installed on the external storage by specifying the android:installLocation attribute. (The default is internal storage.)

When the user uninstalls the application, if the app is installed on internal storage, all files are removed. On the other hand, if the application was installed on external storage, the app files are moved only if we save them in the directory that is obtained from calling API getExternalFilesDir().

To grant everyone permission to your files, you need to declare the following in your manifest file.

<manifest ...>
   <uses-permission android_name=
      "android.permission.READ_EXTERNAL_STORAGE" />
   ...
</manifest>

If we declare READ_EXTERNAL_STORAGE, global read permissions are granted implicitly.

To save files on internal storage, we need to acquire a directory as a file by calling either the getFilesDir() API (which represents an internal directory for your app), or by calling getCacheDir(), which represents your app’s temp cache files.

A new file can be created by specifying the file and the name of the directory where the file needs to be created by using the File constructor as follows.

File file = new File(context.getFilesDir(),
   fileName);

We also can create a file by calling openFileOutput() to get a FileOutputStream.

To create temporary files meant for caching purposes, use the createTempFile() API.

Hands On

Let us create a simple application that demonstrates working with files.

Fire up Android Studio and Start a new Android Studio Project.

File1
Figure 1: Starting a new Android Studio Project

Provide FileDemo as the Application Name and Click Next.

File2
Figure 2: Configuring the new project

On the next screen, leave the default values and click Next.

File3
Figure 3: Leaving the default values in place

On the “Add an activity to Mobile” page, choose “Blank Activity”. This creates an application with a single activity.

File4
Figure 4: Adding a new, blank activity

We are then prompted to customize the activity. We will leave the default values unchanged.

File5
Figure 5: Here is where you would customize the activity (but don’t do so)

Click Finish to creating the project files.

Next, Open the AndroidManifest.xml file.

File6
Figure 6: The AndroidManifest.xml file

We need to declare permissions to write to files here.

<?xmlversion="1.0"encoding="utf-8"?>
<manifestxmlns:android="http://schemas.android.com/apk/
      res/android"
   package="com.example.vipul.filedemo">

   <application
      android_allowBackup="true"
      android_icon="@mipmap/ic_launcher"
      android_label="@string/app_name"
      android_theme="@style/AppTheme">
         <activity
            android_name=".MainActivity"
            android_label="@string/app_name">
               <intent-filter>
                  <actionandroid:name=
                     "android.intent.action.MAIN"/>
                  <categoryandroid:name=
                     "android.intent.category.LAUNCHER"/>
               </intent-filter>
         </activity>
   </application>
   <uses-permissionandroid:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
</manifest>

We are only doing the preceding declaration to demo how to declare what is needed to write to external storage. We now will switch to working with a file on internal storage.

Switch to the design view and add two buttons as shown in the following code.

<RelativeLayoutxmlns:android="http://schemas.android.com/
      apk/res/android"
   xmlns_tools="http://schemas.android.com/tools
      "android:layout_width="match_parent"
   android_paddingRight="@dimen/activity_horizontal_margin"
   android_paddingTop="@dimen/activity_vertical_margin"
   android_paddingBottom="@dimen/activity_vertical_margin
      "tools:context=".MainActivity">

   <TextViewandroid:text="@string/hello_world"
      android_layout_width="wrap_content"
      android_layout_height="wrap_content"
      android_id="@+id/textView"/>

      <Button
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:text="CreateFile"
         android:id="@+id/buttonCreateFile"
         android:layout_below="@+id/textView"
         android:layout_alignLeft="@+id/buttonCreateTempFile"
         android:layout_alignStart="@+id/buttonCreateTempFile"
         android:clickable="true"/>

      <Button
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:text="CreateTempFile"
         android:id="@+id/buttonCreateTempFile"
         android:layout_below="@+id/buttonCreateFile"
         android:layout_toRightOf="@+id/textView"
         android:layout_toEndOf="@+id/textView"
         android:layout_marginTop="41dp"/>

</RelativeLayout>

Next, we will wire up the click event handlers to create files.

Create two method stubs in MainActivity.java

publicvoidsendFileMessage(Viewview){
   //Dosomethinginresponsetobuttonclick
}

publicvoidsendCacheFileMessage(Viewview){
   //Dosomethinginresponsetobuttonclick
}

Next, we will wire up the click events in the layout file.

<Button
   android_layout_width="wrap_content"
   android_layout_height="wrap_content"
   android_text="CreateFile"
   android_id="@+id/buttonCreateFile"
   android_layout_below="@+id/textView"
   android_layout_alignLeft="@+id/buttonCreateTempFile"
   android_layout_alignStart="@+id/buttonCreateTempFile"
   android_clickable="true"
   android:onClick="sendFileMessage"/>

<Button
   android_layout_width="wrap_content"
   android_layout_height="wrap_content"
   android_text="CreateTempFile"
   android_id="@+id/buttonCreateTempFile"
   android_layout_below="@+id/buttonCreateFile"
   android_layout_toRightOf="@+id/textView"
   android_layout_toEndOf="@+id/textView"
   android_layout_marginTop="41dp"
   android:onClick="sendCacheFileMessage"/>

Now, we implement the method stubs to create the files.

public void sendCacheFileMessage(View view) {
   // Do something in response to button click
   File file = new File(view.getContext().getCacheDir(),
      "cachefileName");
   tView = (TextView) findViewById(R.id.textViewStatus);
   tView.setText("cache file create");
   }

   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
      // Inflate the menu; this adds items to the
      // action bar if it is present.
      getMenuInflater().inflate(R.menu.menu_main, menu);
      return true;
}

When we run our application, we will see the home screen as shown in Figure 7.

File7
Figure 7: The home screen, showing the two new buttons

When we click on the “CREATE FILE” button, we will see that a file is created and the Status text changes.

File8
Figure 8: The file has been created

Similarly, when we click on the “CREATE TEMP FILE”, a file is created in the cache directory.

File9
Figure 9: The cache file has been created

We now have created a simple application that works with files.

Summary

In this article, we learned the basics about file and made a simple application that creates files. I hope you have found this information useful.

About the Author

Vipul Patel is a technology geek based in Seattle. He can be reached at vipul.patel@hotmail.com. You can visit his LinkedIn profile at https://www.linkedin.com/pub/vipul-patel/6/675/508.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories