使用openFileOutput()方法获取内部文件的输出流与文件数据的写入,
使用openFileInput()获取内部文件的输入流并将数据读取出来。
activity_main.xml布局:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<EditText
android:id="@+id/et"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="在这里输入内容"
/>
<Button
android:id="@+id/writeBtn"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="保存数据" />
<Button
android:id="@+id/readBtn"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="读取数据" />
<TextView
android:id="@+id/show"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="在这里读入内容"
/>
</LinearLayout>
MainActivity.java布局响应:
package com.example.debug;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
String filename="test";
private EditText et;
private TextView show;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et=(EditText) findViewById(R.id.et);
show=(TextView) findViewById(R.id.show);
findViewById(R.id.readBtn).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
try {
FileInputStream fis=openFileInput(filename);
InputStreamReader is=new InputStreamReader(fis,"utf-8");
char input[]=new char[fis.available()];
is.read(input);
is.close();
fis.close();
String readed=new String(input);
show.setText(readed);
} catch (FileNotFoundException e) {
} catch (UnsupportedEncodingException e) {
} catch (IOException e) {
}
}
});
findViewById(R.id.writeBtn).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
try {
FileOutputStream fos=openFileOutput(filename, Context.MODE_PRIVATE);
OutputStreamWriter osw=new OutputStreamWriter(fos,"utf-8");
osw.write(et.getText().toString());
osw.flush();
fos.flush();
osw.flush();
fos.close();
Toast.makeText(MainActivity.this, "写入完成", Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
} catch (UnsupportedEncodingException e) {
} catch (IOException e) {
}
}
});
}
}
文件的写入和读出都是相对于磁盘的