Android学习之——SD卡操作

在使用模拟器的SD卡前要保证SD卡存在并且可用。创建SD卡可以跟随模拟器一同创建,也可以在adb下通过shell命令创建,文件后缀可随便取,建议选择.img。创建256M的sd卡,命令如下:

   mk sdcard  256M D:/androidTool/sdcard.img

                        

1、设置操作SD卡的权限

<!-- 在SDCard中创建与删除文件权限 --> <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/> <!-- 在SDCard中写文件的权限 --> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>

2、判断手机是否装有SD卡

//判断是否sd卡可用if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){//获得SD卡的路径,测试模拟器2.2获得的路径为/mnt/sdcardString SDPath=Environment.getExternalStorageDirectory()+"/";.......................................//在保存之前需要判断 SDCard 是否存在,并且是否具有可写权限: if(Environment.MEDIA_MOUNTED.endsWith(Environment.getExternalStorageState())) { .... } }

File操作全部代码:

package djx.utils;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import android.os.Environment;import android.util.Log;public class FileUtils {String SDPATH=null;public FileUtils(){SDPATH=Environment.getExternalStorageDirectory()+"/";}//目录不存在创建private void creatDir(String path) throws IOException{File file=new File(SDPATH+path);if(!file.exists())file.mkdirs();}//根据文件名创建文件private File creatFile(String path,String fileName) throws IOException{//创建目录creatDir(path);File file=new File(SDPATH+path,fileName);file.createNewFile();return file;}//判断sd卡上文件是否存在public boolean isFileExit(String path,String fileName){File file=new File(SDPATH+path,fileName);Log.i("is Exit:",String.valueOf(file.exists()));System.out.println("is Exit:"+String.valueOf(file.exists()));return file.exists();}//向SD卡写入数据public File WriteDataToSDCard(String path,String fileName,InputStream inputStream){File file=null;OutputStream outPutStream=null;try {file=creatFile(path,fileName);outPutStream=new FileOutputStream(file);byte buffer[]=new byte[4*1024];while(inputStream.read(buffer)!=-1){outPutStream.write(buffer);}outPutStream.flush();} catch (IOException e) {e.printStackTrace();}finally{try {outPutStream.close();} catch (IOException e) {e.printStackTrace();}}return file;}}

你可能感兴趣的:(Android学习之——SD卡操作)