範例:
main.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"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<EditText
android:id="@+id/input"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<Button
android:id="@+id/write"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Write"
/>
<Button
android:id="@+id/read"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Read"
/>
<TextView
android:id="@+id/output"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
主代碼, AndroidInternalStorage.java
package com.AndroidInternalStorage;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class AndroidInternalStorage extends Activity {
String FILENAME = "MyFile";
EditText edittextInput;
TextView textviewOutput;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
edittextInput = (EditText)findViewById(R.id.input);
Button buttonWrite = (Button)findViewById(R.id.write);
Button buttonRead = (Button)findViewById(R.id.read);
textviewOutput = (TextView)findViewById(R.id.output);
buttonWrite.setOnClickListener(buttonWriteOnClickListener);
buttonRead.setOnClickListener(buttonReadOnClickListener);
}
private Button.OnClickListener buttonWriteOnClickListener
= new Button.OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String string = edittextInput.getText().toString();
FileOutputStream fos;
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}};
private Button.OnClickListener buttonReadOnClickListener
= new Button.OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
FileInputStream fis;
try {
fis = openFileInput(FILENAME);
byte[] input = new byte[fis.available()];
while (fis.read(input) != -1) {}
textviewOutput.setText(new String(input));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}};
}
沒有留言:
發佈留言