android第九步文件的保存和读取
数据存储方式分为
文件
sharedpreferences(参数)
SQLite数据库
内容提供者(Content provider)
网络
一.文件
存储位置:自带存储空间、外存储空间
public class MainActivity extends Activity {
EditText filename;
EditText filecontent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button =(Button)this.findViewById(R.id.button);
button.setOnClickListener(new OnClickListener());
filename = (EditText)this.findViewById(R.id.filename);
filecontent = (EditText)this.findViewById(R.id.filecontent);
}
private final class OnClickListener implements View.OnClickListener
{
@Override
public void onClick(View arg0) {
String filenametext= filename.getText().toString();
String filecontenttext = filecontent.getText().toString();
try
{
FileService file = new FileService(getApplicationContext());
file.save(filenametext, filecontenttext);
Toast.makeText(getApplicationContext(), "成功", 1).show();
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(), "失败", 1).show();
}
}
}
public class FileService {
private Context context; //上下文对象
public FileService(Context context) {
super();
this.context = context;
}
/*
* 保存文件
*
*/
public void save(String filenametext, String filecontenttext) throws Exception {
//文件名称千万不要带路径
//私有操作模式:创建出来的文件只能被本应用访问,其他应用无法访问该文件,
//另外采用私有模式创建的文件,写入文件中的内容会覆盖源文件的内容
FileOutputStream outStream = context.openFileOutput(filenametext,Context.MODE_PRIVATE);
outStream.write(filecontenttext.getBytes());
outStream.close();
}
public String read(String filenametext) throws Exception{
FileInputStream inStream = context.openFileInput(filenametext);
ByteArrayOutputStream outStream = new ByteArrayOutputStream(); //内存流
byte[] buffer = new byte[1024];
int len = 0;
while((len=inStream.read(buffer))!=-1) //读满就返回,可使用循环读完,读完返回值是-1
{
outStream.write(buffer,0,len); //往内存中写数据
}
byte[] data = outStream.toByteArray(); //内存中所有数据
String str = new String(data);
return str;
}
}
public class filetest extends AndroidTestCase {
public void testRun() throws Throwable{
FileService fs = new FileService(this.getContext());
String str=fs.read("text.txt");
Log.i("124", str);
}
}