android 读写SD卡文件

参考:

http://www.oschina.net/code/snippet_176897_7336#11699

写文件:

private void SavedToText(Context context, String stringToWrite) {
if (Environment.MEDIA_MOUNTED.equals(Environment
.getExternalStorageState())) {
String foldername = Environment.getExternalStorageDirectory()
.getPath() + "/log";
File folder = new File(foldername);
if (folder == null || !folder.exists()) {
folder.mkdir();
}
String fileName = "/locLog" + ".txt";
File targetFile = new File(foldername + fileName);
OutputStreamWriter osw;
try {
if (!targetFile.exists()) {
targetFile.createNewFile();
osw = new OutputStreamWriter(new FileOutputStream(
targetFile), "utf-8");
osw.write(stringToWrite);
osw.close();
} else {
osw = new OutputStreamWriter(new FileOutputStream(
targetFile, true), "utf-8");
osw.write("\n" + stringToWrite);
osw.flush();
osw.close();
}
} catch (Exception e) {
// Toast.makeText(context,e.toString(),Toast.LENGTH_LONG).show();
}
} else {
// Toast.makeText(context,"未发现SD卡!",Toast.LENGTH_LONG).show();
} }

读文件:

private String readFromFile(Context context){

        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {

            String foldername = Environment.getExternalStorageDirectory().getPath()+ "/eryaApp";
File folder = new File(foldername); if (folder == null || !folder.exists()) {
folder.mkdir();
} File targetFile=new File("/sdcard/eryaApp/eryaShoppingList.txt");
String readedStr=""; try{
if(!targetFile.exists()){
targetFile.createNewFile();
return "No File error ";
}else{
InputStream in = new BufferedInputStream(new FileInputStream(targetFile));
BufferedReader br= new BufferedReader(new InputStreamReader(in, "UTF-8"));
String tmp; while((tmp=br.readLine())!=null){
readedStr+=tmp;
}
br.close();
in.close(); return readedStr;
}
} catch (Exception e) {
Toast.makeText(context,e.toString(),Toast.LENGTH_LONG).show();
return e.toString();
}
}else{
Toast.makeText(context,"未发现SD卡!",Toast.LENGTH_LONG).show();
return "SD Card error";
} }
上一篇:supervisord监控服务必备命令


下一篇:CountDownLatch——闭锁的实现之一