2012年7月24日 星期二

Android:儲存資料到SD卡

與JAVA中儲存資料至File以及取回概念以及用法相同

<Android Manifest>
要記得將SD卡寫取資料的權限打開
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

<Source Code>

package com.savesdtest;

import ....

public class MainActivity extends Activity {
//datapath為SD卡底下目的資料夾,mydata為儲存資料的TXT檔
        String datapath = "/data1";
String mydata = "note.txt";
File file;

EditText edi;
Button save, get;
TextView show;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

edi = (EditText) findViewById(R.id.editText1);
save = (Button) findViewById(R.id.button1);
get = (Button) findViewById(R.id.button2);
show = (TextView) findViewById(R.id.textView2);
        //利用Environment查看外部儲存空間的狀態是否可讀寫
if (!Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {

} else {
           /*Environment.getExternalStorageDirectory()傳回File,File.getAbsolutePath()
得到SD卡路徑*/
String path = Environment.getExternalStorageDirectory()
.getAbsolutePath() + datapath;
//建立這一個暫時的File物件主要是要用在底下的if判斷式,File.mkdir()
File sdcardPath = new File(path);
if (!sdcardPath.exists()) {
sdcardPath.mkdir();
Toast.makeText(this, path + "已建立", Toast.LENGTH_SHORT).show();
}
file = new File(path + mydata);
}
save.setOnClickListener(new OnClickListener() {

public void onClick(View v) {
// TODO Auto-generated method stub

try {
//JAVA io包裝,位元->字元->字串
FileOutputStream fos = new FileOutputStream(file, true);
OutputStreamWriter osw = new OutputStreamWriter(fos);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(edi.getText().toString());
bw.flush();

bw.close();

} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

});

get.setOnClickListener(new OnClickListener() {

public void onClick(View v) {
// TODO Auto-generated method stub
String str1 = "", str2 = "";
try {
FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
while ((str1 = br.readLine()) != null) {
str2 += str1;
}
show.setText("結果" + str2);
br.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

});
}

}

沒有留言:

張貼留言