Internal Storage
You can
save files directly on the device's internal storage. By default, files saved
to the internal storage are private to your application and other applications
cannot access them (nor can the user). When the user uninstalls your
application, these files are removed.
Creating and Writing into
Internal Storage:
1. Create the File with Specifying mode.
FileOutputStream f =
openFileOutput(<FileName>,<Mode>)
2. Writing into the File.
f.Write();
3. Close the File
f.Close()
Reading File from Internal Storage:
1.
Call FileInputStream with file name and mode.
FileInputStream f
=openFileInput(<FileName>,<Mode>)
2.
Read the File
f.read()
3.
Close the File
f.close()
Example:
InternalStorageTestActivity.java
public class InternalStorageTestActivity extends Activity
{
public static
final String MY_FILE = "MyFile";
public String my_value
= "Testing My File";
/** Called when the activity is first created. */
@Override
public void
onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
//Creating File with name and mode
FileOutputStream
fos = openFileOutput(MY_FILE, Context.MODE_PRIVATE);
//Writing on to the file
fos.write(my_value.getBytes());
//closing the File
fos.close();
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Button
btn = (Button)findViewById(R.id.button1);
final Intent it = new
Intent(getApplicationContext(), TargetActivity.class);
btn.setOnClickListener(new OnClickListener()
{
@Override
public void
onClick(View v)
{
startActivity(it);
}
});
}
}
TargetActivity.java
public class TargetActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void
onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try
{
//Opening the file with File Name
FileInputStream
fip = openFileInput("MyFile.txt");
//Reading the File
fip.read();
//Closing the File
fip.close();
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
No comments:
Post a Comment