Teman-teman mungkin sudah pernah membaca beberapa artikel mengenai Android lainnya. Artikel ini juga akan membahas mengenai cara mengakses dan menulis file menggunakan Android.
Menulis Data ke File
Kelas yang akan digunakan dalam penyimpanan file adalah FileOutputStream dan OutputStreamWriter. Android menyediakan fungsi openFileOutput() yang digunakan untuk membuat file. Coba perhatikan penggalan kode berikut:
// ##### Write a file to the disk ##### /* * We have to use the openFileOutput()-method the ActivityContext * provides, to protect your file from others and This is done for * security-reasons. We chose MODE_WORLD_READABLE, because we have * nothing to hide in our file */ FileOutputStream fOut = openFileOutput(path, MODE_WORLD_READABLE); OutputStreamWriter osw = new OutputStreamWriter(fOut); // Write the string to the file osw.write(bodyOfFile); /* * ensure that everything is really written out and close */ osw.flush(); osw.close(); |
- MODE_APPEND / value = 32768 : akan digunakan oleh fungsi openFileOutput(String, int), jika file sudah ada maka penulisan data ke file yang sifatnya menambah data (tidak menghapus data terlebih dahulu).
- MODE_PRIVATE / value = 0 (default) : akan digunakan oleh fungsi openFileOutput(String, int), file yang dihasilkan hanya dapat diakses oleh aplikasi itu sendiri.
- MODE_WORLD_READABLE / value = 1 : file yang dihasilkan dapat dibaca oleh aplikasi yang lain.
- MODE_WORLD_WRITEABLE / value = 2 : file yang dihasilkan dapat ditulis oleh aplikasi yang lain.
Membaca Data dari File
Kelas yang akan digunakan dalam penyimpanan file adalah InputStream, InputStreamReader dan BufferedReader. Android menyediakan fungsi openFileInput() yang digunakan untuk membaca file. Coba perhatikan penggalan kode berikut:
StringBuffer strBuff = new StringBuffer(); // ##### Read a file from the disk ##### /* * We have to use the openFileInput()-method the ActivityContext * provides, to open the file from disk. */ InputStream is = openFileInput(path); if ( is != null ) { // prepare the file for reading InputStreamReader isr = new InputStreamReader( is ); BufferedReader buff = new BufferedReader(isr); String line; // read every line of the file into the line-variable, on line // at the time while ((line = buff.readLine()) != null ) { // do something with the settings from the file strBuff.append(line); } } |
Contoh Aplikasi
Berikut ini saya akan menuliskan kode program secara lengkap untuk menulis data ke file dan kemudian membacanya:
package com.secangkirkopipanas.android.apps; import java.io.BufferedReader; import java.io.FileOutputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class SavingFileActivity extends Activity { private Button btnSubmit = null ; private Button btnQuit = null ; private EditText txtName = null ; private String fileName = "SampleSavingFile.txt" ; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // setting the view to our newly created layout setContentView(R.layout.main); txtName = (EditText) findViewById(R.id.txtName); // initializing button, including layout parameters btnSubmit = (Button) findViewById(R.id.btnSave); btnSubmit.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { doConfirm(); } }); btnQuit = (Button) findViewById(R.id.btnQuit); btnQuit.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } public void doConfirm() { AlertDialog alertDialog = new AlertDialog.Builder( this ).create(); alertDialog.setTitle( "Sending Request" ); alertDialog .setMessage( "This process will take few seconds. Are you sure want to save to file?" ); final String name = txtName.getText().toString(); alertDialog.setButton( "OK" , new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Log.i( "onClick@doConfirm" , "Click on 'save' button with txtName: " + name); if (saveFile(name, fileName)) { Toast.makeText( SavingFileActivity. this , "The file has been saved with name '" + fileName + "'" , Toast.LENGTH_LONG).show(); String fileContent = readFile(fileName); Toast.makeText(SavingFileActivity. this , fileContent, Toast.LENGTH_LONG).show(); } } }); alertDialog.setIcon(R.drawable.icon); alertDialog.show(); } public boolean saveFile(String content, String path) { try { // catches IOException below final String bodyOfFile = new String(content); // ##### Write a file to the disk ##### /* * We have to use the openFileOutput()-method the ActivityContext * provides, to protect your file from others and This is done for * security-reasons. We chose MODE_WORLD_READABLE, because we have * nothing to hide in our file */ FileOutputStream fOut = openFileOutput(path, MODE_WORLD_READABLE); OutputStreamWriter osw = new OutputStreamWriter(fOut); // Write the string to the file osw.write(bodyOfFile); /* * ensure that everything is really written out and close */ osw.flush(); osw.close(); return true ; } catch (Exception e) { e.printStackTrace(); Toast.makeText(SavingFileActivity. this , e.getMessage(), Toast.LENGTH_LONG).show(); return false ; } } public String readFile(String path) { try { // catches IOException below StringBuffer strBuff = new StringBuffer(); // ##### Read a file from the disk ##### /* * We have to use the openFileInput()-method the ActivityContext * provides, to open the file from disk. */ InputStream is = openFileInput(path); if ( is != null ) { // prepare the file for reading InputStreamReader isr = new InputStreamReader( is ); BufferedReader buff = new BufferedReader(isr); String line; // read every line of the file into the line-variable, on line // at the time while ((line = buff.readLine()) != null ) { // do something with the settings from the file strBuff.append(line.trim()); } } is .close(); return strBuff.toString().trim(); } catch (Exception e) { e.printStackTrace(); Toast.makeText(SavingFileActivity. this , e.getMessage(), Toast.LENGTH_LONG).show(); return null ; } } } |
Selamat mencoba teman-teman, semoga berhasil.
http://secangkirkopipanas.com
Tidak ada komentar:
Posting Komentar