Android中往sd卡中讀寫數據

親測有效。

1.寫到Sd卡中。

public void write(){
    String filePath = null;
    boolean hasSDCard = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    if (hasSDCard) { // SD卡根目錄的
        filePath = Environment.getExternalStorageDirectory().toString() + File.separator + "save.txt";
    } else  // 系統下載緩存根目錄的
        filePath = Environment.getDownloadCacheDirectory().toString() + File.separator + "save.txt";
    try {
        File file = new File(filePath);
        if (!file.exists()) {
            File dir = new File(file.getParent());
            dir.mkdirs();
            file.createNewFile();
        }
        FileOutputStream outStream = new FileOutputStream(file);
        outStream.write((getFirstName()+":"+getLastName()).getBytes());
        outStream.close();
        System.out.print("Done---------------");
    } catch (Exception e) {
        e.printStackTrace();
    }
}
2.從sd卡中讀出。

public String read(){
    StringBuffer strsBuffer = new StringBuffer();
    try {
        // 判斷是否存在SD
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            File file = new File(Environment.getExternalStorageDirectory()
                    .getCanonicalPath() + "/save.txt");
            // 判斷是否存在該文件
            if (file.exists()) {
                // 打開文件輸入流
                FileInputStream fileR = new FileInputStream(file);
                BufferedReader reads = new BufferedReader(
                        new InputStreamReader(fileR));
                String st = null;
                while ((st = reads.readLine()) != null) {
                    strsBuffer.append(st);
                }
                fileR.close();
                return strsBuffer.toString();
            } else {
                System.out.print(strsBuffer.toString());
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

發佈了43 篇原創文章 · 獲贊 14 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章