Você está na página 1de 17

File Handling

in Android
How to read & write file in
Android

Basic Steps
Create new project.
Create interface(main_activity)

File Name
File Text
Write file (Button)
Read file (Button)
Edit text where read data is placed

Basic Steps (cont.)

Create a FileOperations class

FileWriter
BufferedWriter
FileReader
BufferedReader

Create MainActivity.java file


Add permission to manifest

Step 1: done

Project and
Interface is created

Step 2: Create
FileOperations
java Class

=> Create String


path.
=> Create
FileReader/FileWri
ter with path.
Create
BufferedReader/
BufferedWriter.
Read file / write
file.

Step 3: Create MainActivity java file

Use Object of
FileOperations class
for reading and
writing purposes
from in.

Step 4: Add
permission to
manifest

Run AVD and install


you .apk file

Difference between
FileOutputSream & FileWriter
File fout = new
File(file_location_string);
FileOutputStream fos = new
FileOutputStream(fout);
BufferedWriter out = new
BufferedWriter(new
OutputStreamWriter(fos));
out.write("something");

FileWriter fstream = new


FileWriter(file_location_strin
g);
BufferedWriter out = new
BufferedWriter(fstream);
out.write("something");

Difference between
FileOutputSream & FileWriter
FileOutputStream

is meant for writing


streams of raw bytes such as image
data. For writing streams of characters,
consider using FileWriter.
There is actually no difference per se,
FileWriter is just a convenience class.
It extends OutputStreamWriter and
creates the needed FileOutputStream
itself.

Uses of FileOutputSream &


FileWriter
If

you are dealing with binary data (e.g.


an image) use Streams.
If you are using non-ASCII Unicode
characters, e.g. Chinese, use
Readers/Writers.
If you are using ordinary ASCII text (the
traditional 0-127 characters) you can
(usually) use either.

Simple Example of
FileOutputStream
String FILENAME = "hello_file";
String string = "hello world!";
FileOutputStream fos =
openFileOutput(FILENAME,
Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();

Other useful methodes


getFilesDir()

Gets the absolute path to the


filesystem directory where your internal files
are saved.
getDir() Creates (or opens an existing)
directory within your internal storage space.
deleteFile() Deletes a file saved on the
internal storage.
fileList() Returns an array of files currently
saved by your application

How to append data to


existing file
Just

one change.
FileOutputStream fOut =
openFileOutput("savedData.txt",
MODE_APPEND |
MODE_WORLD_READABLE );

Delete a file
You should always delete files that you no
longer need. The most straightforward
way to delete a file is to have the opened
file reference call delete() on itself.
myFile.delete();
If the file is saved on internal storage,
you can also ask the Context to locate
and delete a file by calling deleteFile():
myContext.deleteFile(fileName);

Você também pode gostar