Pada aplikasi ini kita akan membuat sebuah file dan memasukkan isinya serta kita
melakukan read dan write terhadap file tersebut. Buatlah project
baru seperti berikut:
Project Name :
Array2
Build Target : Android 4.2.2
Aplication name : array2
Package name : com.immobulus.array2
Activity :
array2
Min SDK :
9
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<Button android:id="@+id/close"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Close" />
<EditText
android:id="@+id/editor"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:singleLine="false"
android:gravity="top"
/>
</LinearLayout>
file1.java
package com.immobulus.file1;
import
android.app.Activity;
import
android.os.Bundle;
import
android.view.View;
import
android.widget.Button;
import android.widget.EditText;
import
android.widget.Toast;
import
java.io.BufferedReader;
import
java.io.InputStream;
import
java.io.InputStreamReader;
import
java.io.OutputStreamWriter;
public class file1 extends Activity {
private final static String fileku="fileku.txt";
private EditText editor;
@Override
public void onCreate(Bundle
icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
editor=(EditText)findViewById(R.id.editor);
Button
btn=(Button)findViewById(R.id.close);
btn.setOnClickListener(new
Button.OnClickListener() {
public void onClick(View v)
{
finish();
}
});
}
public void onResume() {
super.onResume();
try {
InputStream
in=openFileInput(fileku);
if (in!=null) {
InputStreamReader
tmp=new InputStreamReader(in);
BufferedReader
reader=new BufferedReader(tmp);
String
str;
StringBuilder
buf=new StringBuilder();
while ((str =
reader.readLine()) != null) {
buf.append(str+"\n");
}
in.close();
editor.setText(buf.toString());
}
}
catch
(java.io.FileNotFoundException e) {
}
catch (Throwable t) {
Toast
.makeText(this, "Exception:
"+t.toString(), 2000)
.show();
}
}
public void onPause() {
super.onPause();
try {
OutputStreamWriter
out=
new
OutputStreamWriter(openFileOutput(fileku, 0));
out.write(editor.getText().toString());
out.close();
}
catch (Throwable t) {
Toast
.makeText(this, "Exception:
"+t.toString(), 2000)
.show();
}
}
}
Nama file yang akan kita buat adalah fileku.txt yang didefinisikan dengan coding |
Tidak ada komentar:
Posting Komentar