Android获取sdk路径(通过挂载点)

来源:互联网 发布:如何管控淘宝乱价 编辑:程序博客网 时间:2024/06/06 17:13

废话不多说,直接上代码

package com.example.aaa;import java.io.BufferedInputStream;import java.io.BufferedReader;import java.io.File;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.text.SimpleDateFormat;import java.util.ArrayList;import java.util.Date;import android.annotation.SuppressLint;import android.app.Activity;import android.os.Bundle;import android.os.Environment;import android.util.Log;import android.widget.TextView;public class MainActivity extends Activity {String phonePicsPath;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);TextView txt = (TextView) findViewById(R.id.txt);if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {String[] covertedArray = (String[]) SdCardUtil.getSDCardInfoAbove14(this).toArray(new String[SdCardUtil.getSDCardInfoAbove14(this).size()]);txt.setText(SdCardUtil.getSDCardInfoAbove14(this).toString());} else {txt.setText(SdCardUtil.getSDCardInfoBelow14().toString());}// // Intent intent = new Intent(Intent.ACTION_MAIN);// // intent.addCategory(Intent.CATEGORY_LAUNCHER);// // ComponentName cn = new ComponentName("com.tencent.mobileqq",// // "com.tencent.mobileqq.activity.SplashActivity");// // intent.setComponent(cn);// // startActivity(intent);//// String url = "mqqwpa://im/chat?chat_type=wpa&uin=";// startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));// finish();// String aa = Environment.getExternalStorageDirectory().getPath();// String bb = Environment.getDataDirectory().getPath();// Toast.makeText(this, aa, Toast.LENGTH_SHORT).show();// getPath2();// System.out.println("====================" + getNormalSDCardPath());// 首先判断是否有外部存储卡,如没有判断是否有内部存储卡,如没有,继续读取应用程序所在存储// if(getExternalSdCardPath() != null){// phonePicsPath = getExternalSdCardPath();// }else{// phonePicsPath = getFilesDir().getAbsolutePath();// }// Toast.makeText(this, phonePicsPath, Toast.LENGTH_SHORT).show();}/** * 遍历 "system/etc/vold.fstab” 文件,获取全部的Android的挂载点信息 *  * @return */private static ArrayList<String> getDevMountList() {String[] toSearch = FileUtil.readFile("/system/etc/vold.fstab").split(" ");ArrayList<String> out = new ArrayList<String>();for (int i = 0; i < toSearch.length; i++) {if (toSearch[i].contains("dev_mount")) {if (new File(toSearch[i + 2]).exists()) {out.add(toSearch[i + 2]);}}}return out;}/** * 获取扩展SD卡存储目录 *  * 如果有外接的SD卡,并且已挂载,则返回这个外置SD卡目录 否则:返回内置SD卡目录 *  * @return */public static String getExternalSdCardPath() {// if (SDCardUtils.isMounted()) {// File sdCardFile = new// File(Environment.getExternalStorageDirectory().getAbsolutePath());// return sdCardFile.getAbsolutePath();// }String path = null;File sdCardFile = null;ArrayList<String> devMountList = getDevMountList();for (String devMount : devMountList) {File file = new File(devMount);if (file.isDirectory() && file.canWrite()) {path = file.getAbsolutePath();String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmmss").format(new Date());File testWritable = new File(path, "test_" + timeStamp);if (testWritable.mkdirs()) {testWritable.delete();} else {path = null;}}}if (path != null) {sdCardFile = new File(path);return sdCardFile.getAbsolutePath();}return null;}/** * 获取sd卡路径 双sd卡时,根据”设置“里面的数据存储位置选择,获得的是内置sd卡或外置sd卡 *  * @return */public static String getNormalSDCardPath() {return Environment.getExternalStorageDirectory().getPath();}/** * 获取sd卡路径 双sd卡时,获得的是外置sd卡 *  * @return */public static String getSDCardPath() {String cmd = "cat /proc/mounts";Runtime run = Runtime.getRuntime();// 返回与当前 Java 应用程序相关的运行时对象BufferedInputStream in = null;BufferedReader inBr = null;try {Process p = run.exec(cmd);// 启动另一个进程来执行命令in = new BufferedInputStream(p.getInputStream());inBr = new BufferedReader(new InputStreamReader(in));String lineStr;while ((lineStr = inBr.readLine()) != null) {// 获得命令执行后在控制台的输出信息Log.i("CommonUtil:getSDCardPath", lineStr);if (lineStr.contains("sdcard")&& lineStr.contains(".android_secure")) {String[] strArray = lineStr.split(" ");if (strArray != null && strArray.length >= 5) {String result = strArray[1].replace("/.android_secure","");return result;}}// 检查命令是否执行失败。if (p.waitFor() != 0 && p.exitValue() == 1) {// p.exitValue()==0表示正常结束,1:非正常结束Log.e("CommonUtil:getSDCardPath", "命令执行失败!");}}} catch (Exception e) {Log.e("CommonUtil:getSDCardPath", e.toString());// return Environment.getExternalStorageDirectory().getPath();} finally {try {if (in != null) {in.close();}} catch (IOException e) {e.printStackTrace();}try {if (inBr != null) {inBr.close();}} catch (IOException e) {e.printStackTrace();}}return Environment.getExternalStorageDirectory().getPath();}@SuppressLint("SdCardPath")public String getPath2() {String sdcard_path = null;String sd_default = Environment.getExternalStorageDirectory().getAbsolutePath();Log.d("text", sd_default);if (sd_default.endsWith("/")) {sd_default = sd_default.substring(0, sd_default.length() - 1);}// 得到路径try {Runtime runtime = Runtime.getRuntime();Process proc = runtime.exec("mount");InputStream is = proc.getInputStream();InputStreamReader isr = new InputStreamReader(is);String line;BufferedReader br = new BufferedReader(isr);while ((line = br.readLine()) != null) {if (line.contains("secure"))continue;if (line.contains("asec"))continue;if (line.contains("fat") && line.contains("/mnt/")) {String columns[] = line.split(" ");if (columns != null && columns.length > 1) {if (sd_default.trim().equals(columns[1].trim())) {continue;}sdcard_path = columns[1];}} else if (line.contains("fuse") && line.contains("/mnt/")) {String columns[] = line.split(" ");if (columns != null && columns.length > 1) {if (sd_default.trim().equals(columns[1].trim())) {continue;}sdcard_path = columns[1];}}}} catch (Exception e) {e.printStackTrace();}return sdcard_path;}}

文件工具类:

package com.example.aaa;/*** * 文件工具类 *  * @author zhangda */import java.io.BufferedReader;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.FileWriter;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.util.ArrayList;import java.util.List;import android.text.TextUtils;/** * File Utils * <ul> * Read or write file * <li>{@link #readFile(String)} read file</li> * <li>{@link #readFileToList(String)} read file to string list</li> * <li>{@link #writeFile(String, String, boolean)} write file from String</li> * <li>{@link #writeFile(String, String)} write file from String</li> * <li>{@link #writeFile(String, List, boolean)} write file from String List</li> * <li>{@link #writeFile(String, List)} write file from String List</li> * <li>{@link #writeFile(String, InputStream)} write file</li> * <li>{@link #writeFile(String, InputStream, boolean)} write file</li> * <li>{@link #writeFile(File, InputStream)} write file</li> * <li>{@link #writeFile(File, InputStream, boolean)} write file</li> * </ul> * <ul> * Operate file * <li>{@link #moveFile(File, File)} or {@link #moveFile(String, String)}</li> * <li>{@link #copyFile(String, String)}</li> * <li>{@link #getFileExtension(String)}</li> * <li>{@link #getFileName(String)}</li> * <li>{@link #getFileNameWithoutExtension(String)}</li> * <li>{@link #getFileSize(String)}</li> * <li>{@link #deleteFile(String)}</li> * <li>{@link #isFileExist(String)}</li> * <li>{@link #isFolderExist(String)}</li> * <li>{@link #makeFolders(String)}</li> * <li>{@link #makeDirs(String)}</li> * </ul> *  * @author <a href="http://www.trinea.cn" target="_blank">Trinea</a> 2012-5-12 */public class FileUtil {    public final static String FILE_EXTENSION_SEPARATOR = ".";    private FileUtil() {        throw new AssertionError();    }    /**     * read file     *      * @param filePath     * @param charsetName The name of a supported     *        {@link java.nio.charset.Charset </code>charset<code>}     * @return if file not exist, return null, else return content of file     * @throws RuntimeException if an error occurs while operator BufferedReader     */    public static String readFile(String filePath) {        String fileContent = "";        File file = new File(filePath);        if (file == null || !file.isFile()) {            return null;        }        BufferedReader reader = null;        try {            InputStreamReader is = new InputStreamReader(new FileInputStream(                file));            reader = new BufferedReader(is);            String line = null;            int i = 0;            while ((line = reader.readLine()) != null) {                fileContent += line + " ";            }            reader.close();            return fileContent;        } catch (IOException e) {            e.printStackTrace();        } finally {            if (reader != null) {                try {                    reader.close();                } catch (IOException e) {                    e.printStackTrace();                }            }        }        return fileContent;    }    /**     * write file     *      * @param filePath     * @param content     * @param append is append, if true, write to the end of file, else clear     *        content of file and write into it     * @return return false if content is empty, true otherwise     * @throws RuntimeException if an error occurs while operator FileWriter     */    public static boolean writeFile(String filePath, String content,        boolean append) {        if (StringUtils.isEmpty(content)) {            return false;        }        FileWriter fileWriter = null;        try {            makeDirs(filePath);            fileWriter = new FileWriter(filePath, append);            fileWriter.write(content);            fileWriter.close();            return true;        } catch (IOException e) {            throw new RuntimeException("IOException occurred. ", e);        } finally {            if (fileWriter != null) {                try {                    fileWriter.close();                } catch (IOException e) {                    throw new RuntimeException("IOException occurred. ", e);                }            }        }    }    /**     * write file     *      * @param filePath     * @param contentList     * @param append is append, if true, write to the end of file, else clear     *        content of file and write into it     * @return return false if contentList is empty, true otherwise     * @throws RuntimeException if an error occurs while operator FileWriter     */    public static boolean writeFile(String filePath, List<String> contentList,        boolean append) {        if (contentList == null || contentList.size() == 0) {            return false;        }        FileWriter fileWriter = null;        try {            makeDirs(filePath);            fileWriter = new FileWriter(filePath, append);            int i = 0;            for (String line : contentList) {                if (i++ > 0) {                    fileWriter.write("\r\n");                }                fileWriter.write(line);            }            fileWriter.close();            return true;        } catch (IOException e) {            throw new RuntimeException("IOException occurred. ", e);        } finally {            if (fileWriter != null) {                try {                    fileWriter.close();                } catch (IOException e) {                    throw new RuntimeException("IOException occurred. ", e);                }            }        }    }    /**     * write file, the string will be written to the begin of the file     *      * @param filePath     * @param content     * @return     */    public static boolean writeFile(String filePath, String content) {        return writeFile(filePath, content, false);    }    /**     * write file, the string list will be written to the begin of the file     *      * @param filePath     * @param contentList     * @return     */    public static boolean writeFile(String filePath, List<String> contentList) {        return writeFile(filePath, contentList, false);    }    /**     * write file, the bytes will be written to the begin of the file     *      * @param filePath     * @param stream     * @return     * @see {@link #writeFile(String, InputStream, boolean)}     */    public static boolean writeFile(String filePath, InputStream stream) {        return writeFile(filePath, stream, false);    }    /**     * write file     *      * @param file the file to be opened for writing.     * @param stream the input stream     * @param append if <code>true</code>, then bytes will be written to the end     *        of the file rather than the beginning     * @return return true     * @throws RuntimeException if an error occurs while operator     *         FileOutputStream     */    public static boolean writeFile(String filePath, InputStream stream,        boolean append) {        return writeFile(filePath != null ? new File(filePath) : null, stream,            append);    }    /**     * write file, the bytes will be written to the begin of the file     *      * @param file     * @param stream     * @return     * @see {@link #writeFile(File, InputStream, boolean)}     */    public static boolean writeFile(File file, InputStream stream) {        return writeFile(file, stream, false);    }    /**     * write file     *      * @param file the file to be opened for writing.     * @param stream the input stream     * @param append if <code>true</code>, then bytes will be written to the end     *        of the file rather than the beginning     * @return return true     * @throws RuntimeException if an error occurs while operator     *         FileOutputStream     */    public static boolean writeFile(File file, InputStream stream,        boolean append) {        OutputStream o = null;        try {            makeDirs(file.getAbsolutePath());            o = new FileOutputStream(file, append);            byte data[] = new byte[1024];            int length = -1;            while ((length = stream.read(data)) != -1) {                o.write(data, 0, length);            }            o.flush();            return true;        } catch (FileNotFoundException e) {            throw new RuntimeException("FileNotFoundException occurred. ", e);        } catch (IOException e) {            throw new RuntimeException("IOException occurred. ", e);        } finally {            if (o != null) {                try {                    o.close();                    stream.close();                } catch (IOException e) {                    throw new RuntimeException("IOException occurred. ", e);                }            }        }    }    /**     * move file     *      * @param sourceFilePath     * @param destFilePath     */    public static void moveFile(String sourceFilePath, String destFilePath) {        if (TextUtils.isEmpty(sourceFilePath)            || TextUtils.isEmpty(destFilePath)) {            throw new RuntimeException(                "Both sourceFilePath and destFilePath cannot be null.");        }        moveFile(new File(sourceFilePath), new File(destFilePath));    }    /**     * move file     *      * @param srcFile     * @param destFile     */    public static void moveFile(File srcFile, File destFile) {        boolean rename = srcFile.renameTo(destFile);        if (!rename) {            copyFile(srcFile.getAbsolutePath(), destFile.getAbsolutePath());            deleteFile(srcFile.getAbsolutePath());        }    }    /**     * copy file     *      * @param sourceFilePath     * @param destFilePath     * @return     * @throws RuntimeException if an error occurs while operator     *         FileOutputStream     */    public static boolean copyFile(String sourceFilePath, String destFilePath) {        InputStream inputStream = null;        try {            inputStream = new FileInputStream(sourceFilePath);        } catch (FileNotFoundException e) {            throw new RuntimeException("FileNotFoundException occurred. ", e);        }        return writeFile(destFilePath, inputStream);    }    /**     * read file to string list, a element of list is a line     *      * @param filePath     * @param charsetName The name of a supported     *        {@link java.nio.charset.Charset </code>charset<code>}     * @return if file not exist, return null, else return content of file     * @throws RuntimeException if an error occurs while operator BufferedReader     */    public static List<String> readFileToList(String filePath,        String charsetName) {        File file = new File(filePath);        List<String> fileContent = new ArrayList<String>();        if (file == null || !file.isFile()) {            return null;        }        BufferedReader reader = null;        try {            InputStreamReader is = new InputStreamReader(new FileInputStream(                file), charsetName);            reader = new BufferedReader(is);            String line = null;            while ((line = reader.readLine()) != null) {                fileContent.add(line);            }            reader.close();            return fileContent;        } catch (IOException e) {            throw new RuntimeException("IOException occurred. ", e);        } finally {            if (reader != null) {                try {                    reader.close();                } catch (IOException e) {                    throw new RuntimeException("IOException occurred. ", e);                }            }        }    }    /**     * get file name from path, not include suffix     *      * <pre>     *      getFileNameWithoutExtension(null)               =   null     *      getFileNameWithoutExtension("")                 =   ""     *      getFileNameWithoutExtension("   ")              =   "   "     *      getFileNameWithoutExtension("abc")              =   "abc"     *      getFileNameWithoutExtension("a.mp3")            =   "a"     *      getFileNameWithoutExtension("a.b.rmvb")         =   "a.b"     *      getFileNameWithoutExtension("c:\\")              =   ""     *      getFileNameWithoutExtension("c:\\a")             =   "a"     *      getFileNameWithoutExtension("c:\\a.b")           =   "a"     *      getFileNameWithoutExtension("c:a.txt\\a")        =   "a"     *      getFileNameWithoutExtension("/home/admin")      =   "admin"     *      getFileNameWithoutExtension("/home/admin/a.txt/b.mp3")  =   "b"     * </pre>     *      * @param filePath     * @return file name from path, not include suffix     * @see     */    public static String getFileNameWithoutExtension(String filePath) {        if (StringUtils.isEmpty(filePath)) {            return filePath;        }        int extenPosi = filePath.lastIndexOf(FILE_EXTENSION_SEPARATOR);        int filePosi = filePath.lastIndexOf(File.separator);        if (filePosi == -1) {            return (extenPosi == -1 ? filePath : filePath.substring(0,                extenPosi));        }        if (extenPosi == -1) {            return filePath.substring(filePosi + 1);        }        return (filePosi < extenPosi ? filePath.substring(filePosi + 1,            extenPosi) : filePath.substring(filePosi + 1));    }    /**     * get file name from path, include suffix     *      * <pre>     *      getFileName(null)               =   null     *      getFileName("")                 =   ""     *      getFileName("   ")              =   "   "     *      getFileName("a.mp3")            =   "a.mp3"     *      getFileName("a.b.rmvb")         =   "a.b.rmvb"     *      getFileName("abc")              =   "abc"     *      getFileName("c:\\")              =   ""     *      getFileName("c:\\a")             =   "a"     *      getFileName("c:\\a.b")           =   "a.b"     *      getFileName("c:a.txt\\a")        =   "a"     *      getFileName("/home/admin")      =   "admin"     *      getFileName("/home/admin/a.txt/b.mp3")  =   "b.mp3"     * </pre>     *      * @param filePath     * @return file name from path, include suffix     */    public static String getFileName(String filePath) {        if (StringUtils.isEmpty(filePath)) {            return filePath;        }        int filePosi = filePath.lastIndexOf(File.separator);        return (filePosi == -1) ? filePath : filePath.substring(filePosi + 1);    }    /**     * get folder name from path     *      * <pre>     *      getFolderName(null)               =   null     *      getFolderName("")                 =   ""     *      getFolderName("   ")              =   ""     *      getFolderName("a.mp3")            =   ""     *      getFolderName("a.b.rmvb")         =   ""     *      getFolderName("abc")              =   ""     *      getFolderName("c:\\")              =   "c:"     *      getFolderName("c:\\a")             =   "c:"     *      getFolderName("c:\\a.b")           =   "c:"     *      getFolderName("c:a.txt\\a")        =   "c:a.txt"     *      getFolderName("c:a\\b\\c\\d.txt")    =   "c:a\\b\\c"     *      getFolderName("/home/admin")      =   "/home"     *      getFolderName("/home/admin/a.txt/b.mp3")  =   "/home/admin/a.txt"     * </pre>     *      * @param filePath     * @return     */    public static String getFolderName(String filePath) {        if (StringUtils.isEmpty(filePath)) {            return filePath;        }        int filePosi = filePath.lastIndexOf(File.separator);        return (filePosi == -1) ? "" : filePath.substring(0, filePosi);    }    /**     * get suffix of file from path     *      * <pre>     *      getFileExtension(null)               =   ""     *      getFileExtension("")                 =   ""     *      getFileExtension("   ")              =   "   "     *      getFileExtension("a.mp3")            =   "mp3"     *      getFileExtension("a.b.rmvb")         =   "rmvb"     *      getFileExtension("abc")              =   ""     *      getFileExtension("c:\\")              =   ""     *      getFileExtension("c:\\a")             =   ""     *      getFileExtension("c:\\a.b")           =   "b"     *      getFileExtension("c:a.txt\\a")        =   ""     *      getFileExtension("/home/admin")      =   ""     *      getFileExtension("/home/admin/a.txt/b")  =   ""     *      getFileExtension("/home/admin/a.txt/b.mp3")  =   "mp3"     * </pre>     *      * @param filePath     * @return     */    public static String getFileExtension(String filePath) {        if (StringUtils.isBlank(filePath)) {            return filePath;        }        int extenPosi = filePath.lastIndexOf(FILE_EXTENSION_SEPARATOR);        int filePosi = filePath.lastIndexOf(File.separator);        if (extenPosi == -1) {            return "";        }        return (filePosi >= extenPosi) ? "" : filePath.substring(extenPosi + 1);    }    /**     * Creates the directory named by the trailing filename of this file,     * including the complete directory path required     * to create this directory. <br/>     * <br/>     * <ul>     * <strong>Attentions:</strong>     * <li>makeDirs("C:\\Users\\Trinea") can only create users folder</li>     * <li>makeFolder("C:\\Users\\Trinea\\") can create Trinea folder</li>     * </ul>     *      * @param filePath     * @return true if the necessary directories have been created or the target     *         directory already exists, false one of     *         the directories can not be created.     *         <ul>     *         <li>if {@link FileUtil#getFolderName(String)} return null, return     *         false</li>     *         <li>if target directory already exists, return true</li>     *         <li>return {@link java.io.File#makeFolder}</li>     *         </ul>     */    public static boolean makeDirs(String filePath) {        String folderName = getFolderName(filePath);        if (StringUtils.isEmpty(folderName)) {            return false;        }        File folder = new File(folderName);        return (folder.exists() && folder.isDirectory()) ? true : folder            .mkdirs();    }    /**     * @param filePath     * @return     * @see #makeDirs(String)     */    public static boolean makeFolders(String filePath) {        return makeDirs(filePath);    }    /**     * Indicates if this file represents a file on the underlying file system.     *      * @param filePath     * @return     */    public static boolean isFileExist(String filePath) {        if (StringUtils.isBlank(filePath)) {            return false;        }        File file = new File(filePath);        return (file.exists() && file.isFile());    }    /**     * Indicates if this file represents a directory on the underlying file     * system.     *      * @param directoryPath     * @return     */    public static boolean isFolderExist(String directoryPath) {        if (StringUtils.isBlank(directoryPath)) {            return false;        }        File dire = new File(directoryPath);        return (dire.exists() && dire.isDirectory());    }    /**     * delete file or directory     * <ul>     * <li>if path is null or empty, return true</li>     * <li>if path not exist, return true</li>     * <li>if path exist, delete recursion. return true</li>     * <ul>     *      * @param path     * @return     */    public static boolean deleteFile(String path) {        if (StringUtils.isBlank(path)) {            return true;        }        File file = new File(path);        if (!file.exists()) {            return true;        }        if (file.isFile()) {            return file.delete();        }        if (!file.isDirectory()) {            return false;        }        for (File f : file.listFiles()) {            if (f.isFile()) {                f.delete();            } else if (f.isDirectory()) {                deleteFile(f.getAbsolutePath());            }        }        return file.delete();    }    /**     * get file size     * <ul>     * <li>if path is null or empty, return -1</li>     * <li>if path exist and it is a file, return file size, else return -1</li>     * <ul>     *      * @param path     * @return returns the length of this file in bytes. returns -1 if the file     *         does not exist.     */    public static long getFileSize(String path) {        if (StringUtils.isBlank(path)) {            return -1;        }        File file = new File(path);        return (file.exists() && file.isFile() ? file.length() : -1);    }}

package com.example.aaa;public class SDCardInfo {    /**     * 名称     */    private String label;    /**     * 挂载点     */    private String mountPoint;    /**     * 是否已挂载     */    private boolean mounted;    /**     * @Description:获取SD卡名称     * @return SD卡名称     */    public String getLabel() {        return label;    }    /**     * @Description:设置SD卡名称     * @param label SD卡名称     */    public void setLabel(String label) {        this.label = label;    }    /**     * @Description:获取挂载路径     * @return 挂载路径     */    public String getMountPoint() {        return mountPoint;    }    /**     * @Description:设置挂载路径     * @param mountPoint 挂载路径     */    public void setMountPoint(String mountPoint) {        this.mountPoint = mountPoint;    }    /**     * @Description:是否已经挂载     * @return true:已经挂载,false:未挂载     */    public boolean isMounted() {        return mounted;    }    /**     * @Description:设置是否已经挂载     * @param mounted     *        true:已经挂载,false:未挂载     */    public void setMounted(boolean mounted) {        this.mounted = mounted;    }    @Override    public String toString() {        return "SDCardInfo [label=" + label + ", mountPoint=" + mountPoint + ", mounted=" + mounted + "]";    }}

package com.example.aaa;import java.io.BufferedReader;import java.io.File;import java.io.FileReader;import java.io.IOException;import java.lang.reflect.Method;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import android.annotation.SuppressLint;import android.content.Context;import android.os.Environment;import android.os.storage.StorageManager;@SuppressLint("InlinedApi")public class SdCardUtil {    /**     * 内置     */    static String SDCARD_INTERNAL = "internal";    /**     * 外置     */    static String SDCARD_EXTERNAL = "external";    /**     * API14以下通过读取Linux的vold.fstab文件来获取SDCard信息     *      * @return     */    public static HashMap<String, SDCardInfo> getSDCardInfoBelow14() {        HashMap<String, SDCardInfo> sdCardInfos = new HashMap<String, SDCardInfo>();        BufferedReader bufferedReader = null;        List<String> dev_mountStrs = null;        try {            // API14以下通过读取Linux的vold.fstab文件来获取SDCard信息            bufferedReader = new BufferedReader(new FileReader(Environment.getRootDirectory().getAbsoluteFile() + File.separator + "etc" + File.separator + "vold.fstab"));            dev_mountStrs = new ArrayList<String>();            String line = null;            while ((line = bufferedReader.readLine()) != null) {                if (line.startsWith("dev_mount")) {                    dev_mountStrs.add(line);                }            }            bufferedReader.close();        } catch (IOException e) {            e.printStackTrace();        }                for (int i = 0; dev_mountStrs != null && i < dev_mountStrs.size(); i++) {            SDCardInfo sdCardInfo = new SDCardInfo();            String[] infoStr = dev_mountStrs.get(i).split(" ");            sdCardInfo.setLabel(infoStr[1]);            sdCardInfo.setMountPoint(infoStr[2]);            if (sdCardInfo.getMountPoint().equals(                Environment.getExternalStorageDirectory().getAbsolutePath())) {                sdCardInfo.setMounted(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED));                sdCardInfos.put(SDCARD_INTERNAL, sdCardInfo);            } else if (sdCardInfo.getMountPoint().startsWith("/mnt") && !sdCardInfo.getMountPoint().equals(Environment.getExternalStorageDirectory().getAbsolutePath())) {                File file = new File(sdCardInfo.getMountPoint() + File.separator + "temp");                if (file.exists()) {                    sdCardInfo.setMounted(true);                } else {                    if (file.mkdir()) {                        file.delete();                        sdCardInfo.setMounted(true);                    } else {                        sdCardInfo.setMounted(false);                    }                }                sdCardInfos.put(SDCARD_EXTERNAL, sdCardInfo);            }        }        return sdCardInfos;    }    // API14以上包括14通过改方法获取    public static ArrayList<String> getSDCardInfoAbove14(Context context) {        ArrayList<String> allPath = new ArrayList<String>();        String[] storagePathList = null;        try {            StorageManager storageManager = (StorageManager) context.getSystemService(Context.STORAGE_SERVICE);            Method getVolumePaths = storageManager.getClass().getMethod("getVolumePaths");            storagePathList = (String[]) getVolumePaths.invoke(storageManager);        } catch (Exception e) {            e.printStackTrace();        }                if (storagePathList != null && storagePathList.length > 0) {            String mSDCardPath = storagePathList[0];            allPath.add(mSDCardPath);            if (storagePathList.length >= 2) {                String externalDevPath = storagePathList[1];                allPath.add(externalDevPath);            }        }        return allPath;    }    /**     * @Description:判断SDCard是否挂载上,返回值为true证明挂载上了,否则未挂载     * @param context 上下文     * @param mountPoint 挂载点     */    protected static boolean checkSDCardMount14(Context context, String mountPoint) {        if (mountPoint == null) {            return false;        }        StorageManager storageManager = (StorageManager) context.getSystemService(Context.STORAGE_SERVICE);        try {            Method getVolumeState = storageManager.getClass().getMethod("getVolumeState", String.class);            String state = (String) getVolumeState.invoke(storageManager, mountPoint);            return Environment.MEDIA_MOUNTED.equals(state);        } catch (Exception e) {            e.printStackTrace();        }        return false;    }}

package com.example.aaa;import java.io.UnsupportedEncodingException;import java.net.URLEncoder;import java.util.regex.Matcher;import java.util.regex.Pattern;/** * String Utils *  */public class StringUtils {    private StringUtils() {        throw new AssertionError();    }    /**     * is null or its length is 0 or it is made by space     *      * <pre>     * isBlank(null) = true;     * isBlank("") = true;     * isBlank("  ") = true;     * isBlank("a") = false;     * isBlank("a ") = false;     * isBlank(" a") = false;     * isBlank("a b") = false;     * </pre>     *      * @param str     * @return if string is null or its size is 0 or it is made by space, return     *         true, else return false.     */    public static boolean isBlank(String str) {        return (str == null || str.trim().length() == 0);    }    /**     * is null or its length is 0     *      * <pre>     * isEmpty(null) = true;     * isEmpty("") = true;     * isEmpty("  ") = false;     * </pre>     *      * @param str     * @return if string is null or its size is 0, return true, else return     *         false.     */    public static boolean isEmpty(CharSequence str) {        return (str == null || str.length() == 0);    }    /**     * compare two string     *      * @param actual     * @param expected     * @return     * @see ObjectUtils#isEquals(Object, Object)     */    public static boolean isEquals(String actual, String expected) {        return actual == expected            || (actual == null ? expected == null : actual.equals(expected));    }    /**     * get length of CharSequence     *      * <pre>     * length(null) = 0;     * length(\"\") = 0;     * length(\"abc\") = 3;     * </pre>     *      * @param str     * @return if str is null or empty, return 0, else return     *         {@link CharSequence#length()}.     */    public static int length(CharSequence str) {        return str == null ? 0 : str.length();    }    /**     * null Object to empty string     *      * <pre>     * nullStrToEmpty(null) = "";     * nullStrToEmpty("") = "";     * nullStrToEmpty("aa") = "aa";     * </pre>     *      * @param str     * @return     */    public static String nullStrToEmpty(Object str) {        return (str == null ? "" : (str instanceof String ? (String) str : str            .toString()));    }    /**     * capitalize first letter     *      * <pre>     * capitalizeFirstLetter(null)     =   null;     * capitalizeFirstLetter("")       =   "";     * capitalizeFirstLetter("2ab")    =   "2ab"     * capitalizeFirstLetter("a")      =   "A"     * capitalizeFirstLetter("ab")     =   "Ab"     * capitalizeFirstLetter("Abc")    =   "Abc"     * </pre>     *      * @param str     * @return     */    public static String capitalizeFirstLetter(String str) {        if (isEmpty(str)) {            return str;        }        char c = str.charAt(0);        return (!Character.isLetter(c) || Character.isUpperCase(c)) ? str            : new StringBuilder(str.length()).append(Character.toUpperCase(c))                .append(str.substring(1)).toString();    }    /**     * encoded in utf-8     *      * <pre>     * utf8Encode(null)        =   null     * utf8Encode("")          =   "";     * utf8Encode("aa")        =   "aa";     * utf8Encode("啊啊啊啊")   = "%E5%95%8A%E5%95%8A%E5%95%8A%E5%95%8A";     * </pre>     *      * @param str     * @return     * @throws UnsupportedEncodingException if an error occurs     */    public static String utf8Encode(String str) {        if (!isEmpty(str) && str.getBytes().length != str.length()) {            try {                return URLEncoder.encode(str, "UTF-8");            } catch (UnsupportedEncodingException e) {                throw new RuntimeException(                    "UnsupportedEncodingException occurred. ", e);            }        }        return str;    }    /**     * encoded in utf-8, if exception, return defultReturn     *      * @param str     * @param defultReturn     * @return     */    public static String utf8Encode(String str, String defultReturn) {        if (!isEmpty(str) && str.getBytes().length != str.length()) {            try {                return URLEncoder.encode(str, "UTF-8");            } catch (UnsupportedEncodingException e) {                return defultReturn;            }        }        return str;    }    /**     * get innerHtml from href     *      * <pre>     * getHrefInnerHtml(null)                                  = ""     * getHrefInnerHtml("")                                    = ""     * getHrefInnerHtml("mp3")                                 = "mp3";     * getHrefInnerHtml("<a innerHtml</a>")                    = "<a innerHtml</a>";     * getHrefInnerHtml("<a>innerHtml</a>")                    = "innerHtml";     * getHrefInnerHtml("<a<a>innerHtml</a>")                    = "innerHtml";     * getHrefInnerHtml("<a href="baidu.com">innerHtml</a>")               = "innerHtml";     * getHrefInnerHtml("<a href="baidu.com" title="baidu">innerHtml</a>") = "innerHtml";     * getHrefInnerHtml("   <a>innerHtml</a>  ")                           = "innerHtml";     * getHrefInnerHtml("<a>innerHtml</a></a>")                      = "innerHtml";     * getHrefInnerHtml("jack<a>innerHtml</a></a>")                  = "innerHtml";     * getHrefInnerHtml("<a>innerHtml1</a><a>innerHtml2</a>")        = "innerHtml2";     * </pre>     *      * @param href     * @return <ul>     *         <li>if href is null, return ""</li>     *         <li>if not match regx, return source</li>     *         <li>return the last string that match regx</li>     *         </ul>     */    public static String getHrefInnerHtml(String href) {        if (isEmpty(href)) {            return "";        }        String hrefReg = ".*<[\\s]*a[\\s]*.*>(.+?)<[\\s]*/a[\\s]*>.*";        Pattern hrefPattern = Pattern            .compile(hrefReg, Pattern.CASE_INSENSITIVE);        Matcher hrefMatcher = hrefPattern.matcher(href);        if (hrefMatcher.matches()) {            return hrefMatcher.group(1);        }        return href;    }/**     * process special char in html     *      * <pre>     * htmlEscapeCharsToString(null) = null;     * htmlEscapeCharsToString("") = "";     * htmlEscapeCharsToString("mp3") = "mp3";     * htmlEscapeCharsToString("mp3<") = "mp3<";     * htmlEscapeCharsToString("mp3>") = "mp3\>";     * htmlEscapeCharsToString("mp3&mp4") = "mp3&mp4";     * htmlEscapeCharsToString("mp3"mp4") = "mp3\"mp4";     * htmlEscapeCharsToString("mp3<>&"mp4") = "mp3\<\>&\"mp4";     * </pre>     *      * @param source     * @return     */    public static String htmlEscapeCharsToString(String source) {        return StringUtils.isEmpty(source) ? source : source            .replaceAll("<", "<").replaceAll(">", ">")            .replaceAll("&", "&").replaceAll(""", "\"");    }    /**     * transform half width char to full width char     *      * <pre>     * fullWidthToHalfWidth(null) = null;     * fullWidthToHalfWidth("") = "";     * fullWidthToHalfWidth(new String(new char[] {12288})) = " ";     * fullWidthToHalfWidth("!"#$%&) = "!\"#$%&";     * </pre>     *      * @param s     * @return     */    public static String fullWidthToHalfWidth(String s) {        if (isEmpty(s)) {            return s;        }        char[] source = s.toCharArray();        for (int i = 0; i < source.length; i++) {            if (source[i] == 12288) {                source[i] = ' ';                // } else if (source[i] == 12290) {                // source[i] = '.';            } else if (source[i] >= 65281 && source[i] <= 65374) {                source[i] = (char) (source[i] - 65248);            } else {                source[i] = source[i];            }        }        return new String(source);    }    /**     * transform full width char to half width char     *      * <pre>     * halfWidthToFullWidth(null) = null;     * halfWidthToFullWidth("") = "";     * halfWidthToFullWidth(" ") = new String(new char[] {12288});     * halfWidthToFullWidth("!\"#$%&) = "!"#$%&";     * </pre>     *      * @param s     * @return     */    public static String halfWidthToFullWidth(String s) {        if (isEmpty(s)) {            return s;        }        char[] source = s.toCharArray();        for (int i = 0; i < source.length; i++) {            if (source[i] == ' ') {                source[i] = (char) 12288;                // } else if (source[i] == '.') {                // source[i] = (char)12290;            } else if (source[i] >= 33 && source[i] <= 126) {                source[i] = (char) (source[i] + 65248);            } else {                source[i] = source[i];            }        }        return new String(source);    }}

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.example.aaa"    android:versionCode="1"    android:versionName="1.0" >    <uses-sdk        android:minSdkVersion="8"        android:targetSdkVersion="18" />    <uses-permission android:name="android.permission.WRITE_SETTINGS" >    </uses-permission>    <uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS" />    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>    <application        android:allowBackup="true"        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:theme="@style/AppTheme" >        <activity            android:name="com.example.aaa.MainActivity"            android:label="@string/app_name" >            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>    </application></manifest>

以上代码可直接考到项目中,完美获取,内置外置SD卡都可以获取到

1 0
原创粉丝点击