Android File System

Android file system is similar to disk-based file systems on other platforms.This lesson we are going to learn about android file system with File APIs.

Android devices have two types of storage :


1.Internal storage
2.External storage

Internal storage:


Internal storage is a built-in non-volatile memory.it's memory is available at all the time.Files saved here are accessible by only your app by default.When the application is uninstall the internal storage file has been removed.

External storage:


External storage is a volatile memory.it's memory is available only when the SD card  mounted.It's world-readable, so files saved here may be read outside of your control.When the user uninstalls your app, the system removes your app's files from here only if you save them in the directory from getExternalFilesDir().

You can download source code here.


Output Screen
                                               

Obtain Permissions for External Storage:


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

Create a new project named FileDemo.Create FileActivity.java and insert the following code:

package com.example.filedemo;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

public class FileActivity extends Activity {
ArrayList<String> values = new ArrayList<String>();
Spinner storage;
EditText writeValues;
Button write, read;
String type;
int typePosition;

File file;

FileOutputStream writeContent;
BufferedWriter bw;
FileInputStream readContent;
BufferedReader exReader;
BufferedReader reader;

@Override
protected void onCreate(Bundle savedInstanceState) {
try {

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_file);

values.add("select storage type");
values.add("Internal Storage");
values.add("External Storage");

storage = (Spinner) findViewById(R.id.spinner1);
writeValues = (EditText) findViewById(R.id.editText1);
write = (Button) findViewById(R.id.button1);
read = (Button) findViewById(R.id.button2);

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, values);
storage.setAdapter(adapter);

storage.setOnItemSelectedListener(new OnItemSelectedListener() {

@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {

type = values.get(arg2);
typePosition = arg2;

}

@Override
public void onNothingSelected(AdapterView<?> arg0) {

}

});

write.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {
try {

if (typePosition != 0
&& writeValues.getText().toString().length() != 0) {

if (type.equals("Internal Storage")) {

writeContent = openFileOutput(type + ".txt",
Context.MODE_PRIVATE);
writeContent.write(writeValues.getText()
.toString().getBytes());
Toast.makeText(
FileActivity.this,
"successfully write content to internal storage",
Toast.LENGTH_LONG).show();
writeValues.setText("");

} else if (type.equals("External Storage")) {

if (isExternalStorageWritable()) {

file = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
type + ".txt");
file.createNewFile();
bw = new BufferedWriter(
new OutputStreamWriter(
new FileOutputStream(file)));
bw.write(writeValues.getText().toString());
Toast.makeText(
FileActivity.this,
"successfully write content to external storage",
Toast.LENGTH_LONG).show();
writeValues.setText("");

} else {

Toast.makeText(FileActivity.this,
"External storage not available..",
Toast.LENGTH_LONG).show();

}

}

} else {
Toast.makeText(
FileActivity.this,
"please select storage type and enter value to EditText",
Toast.LENGTH_LONG).show();
}

} catch (Exception e) {
e.printStackTrace();
} finally {
try {
writeContent.close();
bw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
}
}
}
});

read.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
try {

if (typePosition != 0) {

if (type.equals("Internal Storage")) {

readContent = openFileInput(type + ".txt");
reader = new BufferedReader(
new InputStreamReader(readContent));
String readerValue = reader.readLine();
Toast.makeText(FileActivity.this,
"readed content is : " + readerValue,
Toast.LENGTH_LONG).show();

} else if (type.equals("External Storage")) {

if (isExternalStorageWritable()) {

file = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
type + ".txt");
exReader = new BufferedReader(
new InputStreamReader(
new FileInputStream(file)));
String readerValue = exReader.readLine();
Toast.makeText(
FileActivity.this,
"external storage readed content is : "
+ readerValue,
Toast.LENGTH_LONG).show();

} else {
Toast.makeText(FileActivity.this,
"External storage not available..",
Toast.LENGTH_LONG).show();
}

}

} else {

Toast.makeText(FileActivity.this,
"please select storage type",
Toast.LENGTH_LONG).show();

}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
reader.close();
exReader.close();
} catch (Exception e) {
}
}
}
});

} catch (Exception e) {
Log.v("Exception", Log.getStackTraceString(e));
}
}

public boolean isExternalStorageWritable() {
String storageState = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(storageState)) {
return true;
}
return false;
}

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

}

Create the res/layout/activity_file.xml file and insert the following:



<RelativeLayout 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:background="@drawable/images"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".FileActivity" >

    <Spinner
        android:id="@+id/spinner1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="22dp" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/editText1"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="15dp"
        android:text="@string/write_text" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button1"
        android:layout_below="@+id/button1"
        android:layout_marginTop="15dp"
        android:text="@string/read_text" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/spinner1"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="19dp"
        android:ems="10"
        android:hint="@string/hint"
        android:inputType="text" />


</RelativeLayout>

Comments

Popular posts from this blog

SQLiteDatabase With Multiple Tables

Programmatically turn ON/OFF WiFi on Android device

Android Gestures