package com.savefile;
import....
public class MainActivity extends Activity {
Button saveBut,getBut;
EditText edi;
TextView show;
String filename="my.file";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
saveBut=(Button)findViewById(R.id.button1);
getBut=(Button)findViewById(R.id.button2);
edi=(EditText)findViewById(R.id.editText1);
show=(TextView)findViewById(R.id.textView1);
saveBut.setOnClickListener(new OnClickListener(){
public void onClick(View arg0) {
// TODO Auto-generated method stub
try {
//openFileOutput(儲存的檔名,字串連接模式),MODE_APPEND不會覆蓋
掉之前儲存值
FileOutputStream fos=openFileOutput(filename,MODE_APPEND);
//位元組串流轉換為字元組串流,不一定要寫,
//有書會用BufferOutputStream,但雖然會提升效能,但此法會將資料寫
進陣列中,使用上較麻煩
OutputStreamWriter osw=new OutputStreamWriter(fos);
//在這邊我們用BufferedWriter來提升效能
BufferedWriter bw=new BufferedWriter(osw);
bw.write(edi.getText().toString());
bw.flush();
bw.close();
Toast.makeText(MainActivity.this,edi.getText().toString()+"is saved..." , Toast.LENGTH_SHORT).show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
getBut.setOnClickListener(new OnClickListener(){
public void onClick(View arg0) {
// TODO Auto-generated method stub
try {
FileInputStream fis=openFileInput(filename);
InputStreamReader isr=new InputStreamReader(fis);
//使用BufferedReader可以使用readLine()方法非常好用,並可以提升效率
BufferedReader br=new BufferedReader(isr);
String str1="",str2="";
//Java常見用法
while((str1=br.readLine())!=null){
str2+=str1;
show.setText("儲存之值"+str2);
br.close( );
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
沒有留言:
張貼留言