關(guān)于SD卡的路徑在4.0和5.0、6.0不同的問題

在項(xiàng)目中需要將assets目錄下的文件移動到sd卡下然后訪問,然后在4.0時(shí)可以讀寫文件的內(nèi)容,但是到了5.0和6.0的機(jī)型上就無法讀寫并回顯到界面上,上網(wǎng)搜索發(fā)現(xiàn)在不同的android版本下,獲取的sd卡的緩存路徑是不同的。
在4.0時(shí),當(dāng)你使用getCacheDir().getParent().toString()獲得的路徑是 /data/data/<application package>/cache ,但是當(dāng)你在5.0和6.0版本上使用getCacheDir().getParent().toString()時(shí),得到的是 /data/user/0/<application package>.
開始以為是存儲的路徑不對,存儲時(shí)需要分版本,但是通過log打印發(fā)現(xiàn)存取路徑是能對應(yīng)上的,最終發(fā)現(xiàn)是文件讀取權(quán)限的問題。

這是條目回顯的代碼,開始一直彈toastCan't read from data.user.0.<application package>.config.txt
"所以一直在找路徑問題。

public String getConfigItem(String key) {
        assert key != null;
        String pkgDirString = getCacheDir().getParent().toString();
        
        String filePath = pkgDirString + File.separator + CONF_FILENAME;//config.txt
        String value = null;
        try {
            value = FileParser.getProfileString(filePath, key);
        } catch (IOException e) {
            Toast.makeText(this, "Can't read from " + filePath,
                    Toast.LENGTH_SHORT).show();
        }
        return value;
    }

public static String getProfileString(String file, String key)
            throws IOException {
        String strLine, value;
        BufferedReader br = new BufferedReader(new FileReader(file), 1024);
        try {
            while ((strLine = br.readLine()) != null) {
                strLine = strLine.trim();
                strLine = strLine.split("[;#]")[0];

                strLine = strLine.trim();
                String[] strArray = strLine.split("=");
                if (strArray.length == 1) {
                    value = strArray[0].trim();
                    if (value.equals(key)) {
                        value = "";
                        return value;
                    }
                } else if (strArray.length == 2) {
                    value = strArray[0].trim();
                    if (value.equals(key)) {
                        value = strArray[1].trim();
                        return value;
                    }
                } else if (strArray.length > 2) {
                    value = strArray[0].trim();
                    if (value.equals(key)) {
                        value = strLine.substring(strLine.indexOf("=") + 1)
                                .trim();
                        return value;
                    }
                }
            }
        } finally {
            br.close();
        }
        return null;
    }

后來尋找了好久最終發(fā)現(xiàn)文件根本沒有從assets目錄下轉(zhuǎn)移到sd卡中,于是去那邊的代碼中進(jìn)行尋找。

//獲得android版本
        androidVersion = SystemCommands.getAndroidVersion();
        SystemCommands.copyFilesFromAssets(getAssets(), androidVersion);

然后是copyFilesFromAssets(getAssets(), androidVersion)的代碼



public static boolean copyFilesFromAssets(AssetManager am,
            int androidVersion) {
String certs_dirname = "certs";//證書目錄名
boolean is64cpu = SystemCommands.checkIfCPUx86();
if (androidVersion >= 21) {//5.0以上
if(is64cpu){        
String filenames[] = { "config.txt", "vpn-client5-64", "help.pdf","monitorvpn.sh" };
for (String filename : filenames) {
//寫入app文件目錄下
String toString = APP_PATH+ File.separator + filename;
// skip config file except the first time
if (filename == "config.txt" && new File(toString).exists()) {
    continue;
    }
Log.v(TAG, "copying " + filename + " to " + toString);
copyFileAndChmod(am, filename, toString, "777");
}
}else{
String filenames[] = { "config.txt", "vpn-client5-32", "help.pdf","monitorvpn.sh" };
for (String filename : filenames) {
String toString = APP_PATH + File.separator + filename;
// skip config file except the first time
if (filename == "config.txt" && new File(toString).exists()) {
    continue;
    }

Log.v(TAG, "copying " + filename + " to " + toString);
copyFileAndChmod(am, filename, toString, "777");
    }
    }
} else {
String filenames[] = { "config.txt", "vpn-client4", "help.pdf","monitorvpn.sh" };
for (String filename : filenames) {
String toString = APP_PATH + File.separator + filename;
// skip config file except the first time
if (filename == "config.txt" && new File(toString).exists()) {
continue;
}
Log.v(TAG, "copying " + filename + " to " + toString);
copyFileAndChmod(am, filename, toString, "755");
}
}



protected static boolean copyFileAndChmod(AssetManager am, String src_path,
            String tgt_path, String mode) {
        if (null == mode) {
            mode = "777";
        }
        // Log.v(TAG, "src=" + src_path + ", target=" + tgt_path);
        try {
            //獲取assets某文件的內(nèi)容。    src_path文件名
            InputStream is = am.open(src_path);
            //拷貝到的地址
            copyFileFromStream(is, tgt_path);
            
            //755  管理者擁有的權(quán)限  與管理者同組的人擁有的權(quán)限  其他人擁有的權(quán)限
            //111 101 101 可讀可寫可執(zhí)行  可讀可執(zhí)行    修改文件權(quán)限。
            
            executeCommnad("chmod  " + mode + " " + tgt_path);
            
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
        
    }
    
    
    
        //將is內(nèi)容寫到target_path路徑下
    public static boolean copyFileFromStream(InputStream is, String target_path) {
        try {
            FileOutputStream fos = new FileOutputStream(target_path);
            int len = 0;
            byte[] b = new byte[is.available()];
            while ((len = is.read(b)) != -1) {
                fos.write(b, 0, len);
            }
            fos.flush();
            if (null != is) {
                is.close();
            }
            if (null != fos) {
                fos.close();
            }
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }


public static String executeCommnad(String args) {
        String line, result = "";
        try {
            Process process;
            if (args != null) {
                process = Runtime.getRuntime().exec(args);
            } else {
                process = Runtime.getRuntime().exec("ls");
            }
        } catch (Throwable t) {
            t.printStackTrace();
            return null;
        }
        return "ok";
    }

最后把權(quán)限5.0和6.0的權(quán)限改成777就可以正常使用config文件了。問題解決了。。。。。

還有很多人對于存儲路徑很模糊,在這里寫一下。
當(dāng)SD卡存在或者SD卡不可被移除的時(shí)候,就調(diào)用getExternalCacheDir()方法來獲取緩存路徑,否則就調(diào)用getCacheDir()方法來獲取緩存路徑。前者獲取到的就是 /sdcard/Android/data/<application package>/cache 這個(gè)路徑,而后者獲取到的是 /data/data/<application package>/cache 這個(gè)路徑。

public String getDiskCacheDir(Context context) {  
    String cachePath = null;  
    if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())  
            || !Environment.isExternalStorageRemovable()) {  
        cachePath = context.getExternalCacheDir().getPath();  
    } else {  
        cachePath = context.getCacheDir().getPath();  
    }  
    return cachePath;  
} 

應(yīng)用程序在運(yùn)行的過程中如果需要向手機(jī)上保存數(shù)據(jù),一般是把數(shù)據(jù)保存在SDcard中的。
大部分應(yīng)用是直接在SDCard的根目錄下創(chuàng)建一個(gè)文件夾,然后把數(shù)據(jù)保存在該文件夾中。
這樣當(dāng)該應(yīng)用被卸載后,這些數(shù)據(jù)還保留在SDCard中,留下了垃圾數(shù)據(jù)。
如果你想讓你的應(yīng)用被卸載后,與該應(yīng)用相關(guān)的數(shù)據(jù)也清除掉,該怎么辦呢?
通過Context.getExternalFilesDir()方法可以獲取到 SDCard/Android/data/你的應(yīng)用的包名/files/ 目錄,一般放一些長時(shí)間保存的數(shù)據(jù)
通過Context.getExternalCacheDir()方法可以獲取到 SDCard/Android/data/你的應(yīng)用包名/cache/目錄,一般存放臨時(shí)緩存數(shù)據(jù)
如果使用上面的方法,當(dāng)你的應(yīng)用在被用戶卸載后,SDCard/Android/data/你的應(yīng)用的包名/ 這個(gè)目錄下的所有文件都會被刪除,不會留下垃圾信息。
而且上面二個(gè)目錄分別對應(yīng) 設(shè)置->應(yīng)用->應(yīng)用詳情里面的”清除數(shù)據(jù)“與”清除緩存“選項(xiàng)
如果要保存下載的內(nèi)容,就不要放在以上目錄下。

同時(shí)區(qū)別下面兩個(gè)方法
getCacheDir()方法用于獲取/data/data/<application package>/cache目錄
getFilesDir()方法用于獲取/data/data/<application package>/files目錄

android程序掃描儲存時(shí),如果使用API:Environment.getExternalStorageDirectory().getPath()獲得的是默

可以先判斷下Environment.getExternalStorageDirectory().getParentFile(),如果返回null則沒有父路徑,取Environment.getExternalStorageDirectory().getPath()為當(dāng)前父路徑。

Android開發(fā):filePath放在哪個(gè)文件夾

Environment.getDataDirectory() = /data
Environment.getDownloadCacheDirectory() = /cache
Environment.getExternalStorageDirectory() = /mnt/sdcard
Environment.getExternalStoragePublicDirectory(“test”) = /mnt/sdcard/test
Environment.getRootDirectory() = /system
getPackageCodePath() = /data/app/com.my.app-1.apk
getPackageResourcePath() = /data/app/com.my.app-1.apk
getCacheDir() = /data/data/com.my.app/cache
getDatabasePath(“test”) = /data/data/com.my.app/databases/test
getDir(“test”, Context.MODE_PRIVATE) = /data/data/com.my.app/app_test
getExternalCacheDir() = /mnt/sdcard/Android/data/com.my.app/cache
getExternalFilesDir(“test”) = /mnt/sdcard/Android/data/com.my.app/files/test
getExternalFilesDir(null) = /mnt/sdcard/Android/data/com.my.app/files
getFilesDir() = /data/data/com.my.app/files

參考博客:http://blog.csdn.net/qingzi635533/article/details/51274116

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 230,791評論 6 545
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 99,795評論 3 429
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 178,943評論 0 384
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 64,057評論 1 318
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 72,773評論 6 414
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 56,106評論 1 330
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼。 笑死,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 44,082評論 3 450
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 43,282評論 0 291
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 49,793評論 1 338
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 41,507評論 3 361
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 43,741評論 1 375
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,220評論 5 365
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 44,929評論 3 351
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,325評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,661評論 1 296
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 52,482評論 3 400
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 48,702評論 2 380

推薦閱讀更多精彩內(nèi)容