讀寫記憶卡文字檔
發表人:
Seachaos
積分: 2432
積分: 2432
以下是Android讀寫記憶卡檔案的程式碼
[sea:javaCode]
String str = "Write Test";
try {
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
File ofe = new File(Environment.getExternalStorageDirectory()+"/test.txt");
if(!ofe.exists())
ofe.createNewFile();
// write string
FileWriter fo = new FileWriter(ofe);
fo.write(str);
// read to string
FileReader fi = new FileReader(ofe);
fi.read(str.toCharArray());
vtext.setText(str);
}else{
vtext.setText("Not SD Card");
}
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
[/sea]
[sea:javaCode]
String str = "Write Test";
try {
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
File ofe = new File(Environment.getExternalStorageDirectory()+"/test.txt");
if(!ofe.exists())
ofe.createNewFile();
// write string
FileWriter fo = new FileWriter(ofe);
fo.write(str);
// read to string
FileReader fi = new FileReader(ofe);
fi.read(str.toCharArray());
vtext.setText(str);
}else{
vtext.setText("Not SD Card");
}
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
[/sea]
發表人:
Seachaos
積分: 2432
積分: 2432
這斷程式碼特別需要注意
[sea:javaCode]
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
...
}
[/sea]
這是判斷Android是否有安裝記憶卡
要用equals來判斷,如果寫成以下方式是無法成功判別的
[sea:javaCode]
if(Environment.getExternalStorageState()==Environment.MEDIA_MOUNTED){
...
}
[/sea]
[sea:javaCode]
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
...
}
[/sea]
這是判斷Android是否有安裝記憶卡
要用equals來判斷,如果寫成以下方式是無法成功判別的
[sea:javaCode]
if(Environment.getExternalStorageState()==Environment.MEDIA_MOUNTED){
...
}
[/sea]