操作内存卡的惯用代码
操作内存卡的常用代码
1.操作权限 <!-- SD卡写入 --> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.DELETE_CACHE_FILES" />
2.获取文件保存路径
// 获取保存路径 public File getFilePath() { File filePath = null; //判断SD卡存在与否 if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { filePath = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+ "/A_Test/test/"); if (!filePath.isDirectory()) {//判断文件存在与否,不存在就创建 filePath.mkdirs(); } } else { Toast.makeText(Main.this, "存储卡不存在,请插入卡!", 3000).show(); } return filePath; }
3.获取图片保存路径
// 获得SD的路径 public String getSDPath() { File sdPath = null; if (Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED)) { // sd卡存在 sdPath = new File(Environment.getExternalStorageDirectory() .getAbsolutePath() + File.separator + "mobileoa" + File.separator + "photo");// 获得路径 // sdPath = new File(Environment.getExternalStorageDirectory() // .getAbsolutePath());// 获得根路径 } return sdPath != null ? sdPath.toString() : "内存卡不存在!"; } // 获得SDCard下图片的路径 private List<String> getSDCard() { imagePaths = new ArrayList<String>(); try { File file = new File(getSDPath()); File[] files = file.listFiles(); for (File theFile : files) { if (isImageFile(theFile.getPath())) { imagePaths.add(theFile.getPath()); } } } catch (Exception e) { return imagePaths; } return imagePaths; } // 判断是否是图片文件 private boolean isImageFile(String fileName) { String extension = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()).toLowerCase(); if (extension.equals("jpg") || extension.equals("png") || extension.equals("gif") || extension.equals("jpeg") || extension.equals("bmp")) { return true; } return false; }