Thursday, 22 March 2012
Read write file android
layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<EditText
android:id="@+id/myEditText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="New To Do Item"
/>
<ListView
android:id="@+id/myListView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
for internal file
protected void readFile()
{
try {
String file = "input.txt";
FileInputStream finp = openFileInput(file);
InputStreamReader isr = new InputStreamReader(finp, "UTF8");
BufferedReader br = new BufferedReader(isr);
String line ="";
while((line = br.readLine()) != null){
myEditText.setText(line);
}
br.close();
isr.close();
} catch (Exception e) {
myEditText.setText(e.toString());
// TODO: handle exception
}
}
protected void writeFile()
{
try {
String file = "input.txt";
FileInputStream finp = openFileInput(file);
InputStreamReader isr = new InputStreamReader(finp, "UTF8");
BufferedReader br = new BufferedReader(isr);
String line ="";
int total = 0;
while((line = br.readLine()) != null){
//myEditText.setText(line);
try {
total += Integer.parseInt(line);
} catch(NumberFormatException nfe) {
System.out.println("Could not parse " + nfe);
}
}
br.close();
isr.close();
file = "output.txt";
FileOutputStream fout = openFileOutput(file, MODE_WORLD_WRITEABLE);
OutputStreamWriter osw = new OutputStreamWriter(fout, "UTF8");
BufferedWriter bw = new BufferedWriter(osw);
bw.write(Integer.toString(total));
//bw.write("helo");
bw.close();
osw.close();
} catch (Exception e) {
myEditText.setText(e.toString());
// TODO: handle exception
}
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment