一 效果图
二 代码
MainActivity
package com.example.filepersistencetest;
import java.io.File;
import java.io.FileOutputStream;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
private EditText edit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edit = (EditText) findViewById(R.id.edit);
public void savetoSD(String filename,String filecontent)throws Exception{
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
File file=new File(Environment.getExternalStorageDirectory(),filename);
FileOutputStream out=new FileOutputStream(file);
out.write(filecontent.getBytes());
out.close();
Toast.makeText(getApplicationContext(), R.string.success, 1).show();
}else{
Toast.makeText(getApplicationContext(), R.string.fail, 1).show();
}
}
public void onDestory()
{
super.onDestroy();
String input=edit.getText().toString();
try{
savetoSD("data",input);
}catch(Exception e){
e.printStackTrace();
}
}
}
xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<EditText
android:id="@+id/edit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Type something here"
/>
</LinearLayout>