Blog

0

File System di Android

Cara baca dan tulis yang biasa digunakan di Java tidak bisa digunakan dalam Android karena Security-Model di Android tidak memperbolehkannya. Setiap apk yang terinstall memiliki id masing-masing dimana id ini digunakan untuk mengakses “sandbox”-nya. Mungkin mirip dengan private storage yang hanya bisa diakses oleh apk tersebut. Oleh karena itu, code seperti ini tidak akan berfungsi di Android

[sourcecode language="java"]
FileWriter f = new FileWriter("impossible.txt");
// throws: ‘java.io.FileNotFoundException: /impossible.txt ‘
[/sourcecode]

Namun, menulis ke sdcard bisa dilakukan dengan method Java standar

[sourcecode language="java"]
FileWriter f = new FileWriter("/sdcard/download/possible.txt");
[/sourcecode]

Untuk mengakses file menggunakan Android, digunakan cara sebagai berikut

[sourcecode language="java"]
try { // catches IOException below
final String TESTSTRING = new String("Hello Android");

// ##### Write a file to the disk #####
FileOutputStream fOut = openFileOutput("samplefile.txt",
MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);

// Write the string to the file
osw.write(TESTSTRING);
osw.flush();
osw.close();

// ##### Read the file back in #####

FileInputStream fIn = openFileInput("samplefile.txt");
InputStreamReader isr = new InputStreamReader(fIn);
char[] inputBuffer = new char[TESTSTRING.length()];
// Fill the Buffer with data from the file
isr.read(inputBuffer);
// Transform the chars to a String
String readString = new String(inputBuffer);

// Check if we read back the same chars that we had written out
boolean isTheSame = TESTSTRING.equals(readString);

// WOHOO lets Celebrate =)
Log.i("File Reading stuff", "success = " + isTheSame);

} catch (IOException ioe) {
ioe.printStackTrace();
}
[/sourcecode]

Namun untuk path nama file, saat ini terbatas tidak mengandung ‘/’ alias belum support direktorisasi sehingga saat ini, semua file yang ditulis disimpan dalam sebuah folder yang sama.

Sumber: http://www.anddev.org/working_with_files-t115.html

Comments

There are no comments yet.

Leave a Reply

Your email is never published nor shared. Required fields are marked *

*

© Copyright PT Javan Cipta Solusi 2012. All rights reserved.