要往SDCard存放文件,程序必须先判断手机是否装有SDCard,并且可以进行读写。
注意:访问SDCard必须在AndroidManifest.xml中加入访问SDCard的权限
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
File sdCardDir = Environment.getExternalStorageDirectory();//获取SDCard目录
File saveFile = new File(sdCardDir, “XXXX.txt”);
FileOutputStream outStream = new FileOutputStream(saveFile);
outStream.write("把文件存放在SDCard".getBytes());
outStream.close();
}
Environment.getExternalStorageState()方法用于获取SDCard的状态,如果手机装有SDCard,并且可以进行读写,那么方法返回的状态等于Environment.MEDIA_MOUNTED。
Environment.getExternalStorageDirectory()方法用于获取SDCard的目录,当然要获取SDCard的目录,
你可以这样写:
File saveFile = new File("/sdcard/XXXX.txt");
FileOutputStream outStream = new FileOutputStream(saveFile);
outStream.write("把文件存放在SDCard".getBytes());
outStream.close();