问题描述
- 小白请教高手问题,今天看了持久化技术的关于一个从文件中读取数据的问题
-
想要完成一个功能,向EditText里输入数据,数据存放在一个文件夹后,然后按下back键,再重新启动这个程序,再从这个文件里读取数据,出现的是这个数据已经填充在EditText里
下面是代码MainActivity
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.EditText;
import android.widget.Toast;public class MainActivity extends Activity {
EditText text;
String content;
FileOutputStream out=null;
BufferedWriter writer=null;
BufferedReader reader=null;
StringBuilder builder;
String str;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text=(EditText)findViewById(R.id.text);
str=load();
if(!TextUtils.isEmpty(str)){
text.setText(str);
text.setSelection(str.length());
Toast.makeText(getApplicationContext(), "You have succeed!!!",Toast.LENGTH_LONG).show();
}
}
protected void onDestroy() {
super.onDestroy();
content=text.getText().toString();
save(content);
}public void save(String content) { try{ FileOutputStream out = openFileOutput("data",Context.MODE_PRIVATE); writer=new BufferedWriter(new OutputStreamWriter(out)); writer.write(content); }catch(IOException e){ e.printStackTrace(); }finally{ try{ if(writer!=null){ writer.close(); } }catch(IOException e){ e.printStackTrace(); } } } public String load(){ try{ FileInputStream in=openFileInput("data"); reader=new BufferedReader(new InputStreamReader(in)); StringBuilder builder= new StringBuilder(); String line; if((line=reader.readLine())!=null){ builder.append(line); } }catch(IOException e){ e.printStackTrace(); }finally{ if(reader!=null){ try{ reader.close(); }catch(final IOException e){ e.printStackTrace(); } } } return builder.toString(); }
}
activity_main
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.IWIN.filepersistencetext.MainActivity" ><EditText android:id="@+id/text" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:hint="type something..." />
解决方案
http://blog.sina.com.cn/s/blog_90cdca4c01012eo5.html