Android 文件的保存與讀取之SDCard(SD卡)存儲(chǔ)

Android鐘對(duì)數(shù)據(jù)的存儲(chǔ)與訪問是很有必要的,在Android中對(duì)于數(shù)據(jù)存儲(chǔ)提供了如下幾種方法:

文件形式
SharedPreferences(參數(shù)-鍵值對(duì)形式)
SQLite數(shù)據(jù)庫(空間2T)
Content provider (Android組件-內(nèi)容提供者)
網(wǎng)絡(luò)(云存儲(chǔ))
現(xiàn)在我們主要寫的是文件的保存與讀取闭专。

Android文件儲(chǔ)存數(shù)據(jù)有兩個(gè)地方:1贱勃、Android系統(tǒng)自帶的存儲(chǔ)空間乾闰,2色罚、外部?jī)?chǔ)存設(shè)備(SD等)

寫的是第二種SDCard(SD卡)存儲(chǔ):

JAVA代碼:

1追葡、Activity類代碼:

package com.example.administrator.foundationdemo.file;

import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.foundationdemo.R;

public class FileActivity extends AppCompatActivity {

    private EditText file_name_edittext;
    private EditText file_text_edittext;
    private Button file_writing_button;
    private Button file_read_button;
    private TextView file_read_text;

    FileService fileService;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_file);

        file_name_edittext = (EditText) findViewById(R.id.file_name_edittext);
        file_text_edittext = (EditText) findViewById(R.id.file_text_edittext);
        file_writing_button = (Button) findViewById(R.id.file_writing_button);
        file_read_button = (Button) findViewById(R.id.file_read_button);
        file_read_text = (TextView) findViewById(R.id.file_read_text);

        fileService = new FileService(FileActivity.this);

        //數(shù)據(jù)保存按鈕
        file_writing_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String fileName = file_name_edittext.getText().toString();
                String fileText = file_text_edittext.getText().toString();


                try {
                    //判斷SDCard是否存在并且可寫
                    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
                        fileService.saveToSDCard(fileName,fileText);
                        Toast.makeText(FileActivity.this,"保存成功",Toast.LENGTH_LONG).show();
                    }else {
                        Toast.makeText(FileActivity.this,"SDCard不存在或不可寫",Toast.LENGTH_LONG).show();
                    }
                } catch (Exception e) {
                    Toast.makeText(FileActivity.this,"保存失敗",Toast.LENGTH_LONG).show();
                    e.printStackTrace();
                }
            }
        });

        //數(shù)據(jù)讀取按鈕
        file_read_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String fileName = file_name_edittext.getText().toString();
                try {
                    file_read_text.setText(fileService.read(fileName));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
}

FileService類代碼:

package com.example.administrator.foundationdemo.file;

import android.content.Context;
import android.os.Environment;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

/**
 * Created by Administrator on 2016/11/30.
 */
public class FileService {

    Context context;

    public FileService(){

    }

    public FileService(Context context){
        this.context = context;
    }

    /**Android自帶內(nèi)存的文件儲(chǔ)存
     *
     * @param fileName 文件名稱 文件類容
     * @param fileText
     * @throws Exception
     */
    public void writing(String fileName, String fileText) throws Exception{
        //默認(rèn)保存路徑../data/date/package name/file目錄下
        //Android還提供了兩種方法getCacheDir()和getFilesDir()方法:
        //getCacheDir()方法用于獲取/data/data/<package name>/cache目錄
        //getFilesDir()方法用于獲取/data/data/<package name>/file目錄

        //openFileOutput(Sting 预皇,int) 快速獲取一個(gè)輸出流,Sting==>文件名稱逮诲,int操作模式(可看源碼信息)
        //Context.MODE_PRIVATE:為默認(rèn)操作模式帜平,代表該文件是私有數(shù)據(jù),只能被該應(yīng)用訪問梅鹦,在該模式下裆甩,寫入的內(nèi)容會(huì)覆蓋源文件的內(nèi)容;
        //Context.MODE_APPEND:為追加操作模式齐唆,代表該文件是私有的嗤栓,只能夠被該應(yīng)用訪問,在該模式下箍邮,寫入的內(nèi)容追加在源文件內(nèi)容的后面茉帅;
        ////還有一種追加方式為FileoutputStream中的兩個(gè)參數(shù)(String name,boolean append)其中第二個(gè)參數(shù)決定是否以追加的模式來寫入內(nèi)容;
        //Context.MODE_READABLE:表示當(dāng)前文件能被其他應(yīng)用讀取;
        // Context.MODE_WRITEABLE:表示當(dāng)前文件能被其他應(yīng)用寫入;
        FileOutputStream fileOutputStream = context.openFileOutput(fileName,Context.MODE_PRIVATE);
        fileOutputStream.write(fileText.getBytes());
        fileOutputStream.close();

    }

    /**將文件存放在SDCard
     * 需要權(quán)限
     * 在SDCard中創(chuàng)建與刪除文件權(quán)限
     * <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
     * 往SDCard寫入數(shù)據(jù)權(quán)限
     * <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
     * @param fileName 文件名稱
     * @param fileText 文件內(nèi)容
     * @throws Exception
     */

    public void saveToSDCard(String fileName, String fileText) throws Exception{
        //第一個(gè)參數(shù)方法為獲取SDCard目錄
        File file = new File(Environment.getExternalStorageDirectory(),fileName);
        FileOutputStream outputStream = new FileOutputStream(file);
        outputStream.write(fileText.getBytes());
        outputStream.close();
    }


    public String read(String fileName) throws Exception{
        //默認(rèn)讀取路徑../data/date/package name/file目錄下
        FileInputStream fileInputStream = context.openFileInput(fileName);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = fileInputStream.read(buffer)) != -1){
            outputStream.write(buffer,0,len);
        }

        return new String(outputStream.toByteArray());
    }

}

XML代碼:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".file.FileActivity">

    <EditText
        android:id="@+id/file_name_edittext"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:singleLine="true"
        android:hint="請(qǐng)輸入文件名稱"/>
    <EditText
        android:id="@+id/file_text_edittext"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:minLines="3"
        android:hint="請(qǐng)輸入文件內(nèi)容"/>
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <Button
            android:id="@+id/file_writing_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="保存"/>
        <Button
            android:id="@+id/file_read_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="讀取"/>
    </LinearLayout>

    <TextView
        android:id="@+id/file_read_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

效果圖:

這里寫圖片描述

希望對(duì)你們有幫助_缎稹!55小Kち病廷蓉!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末全封,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子桃犬,更是在濱河造成了極大的恐慌刹悴,老刑警劉巖,帶你破解...
    沈念sama閱讀 216,496評(píng)論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件攒暇,死亡現(xiàn)場(chǎng)離奇詭異土匀,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)形用,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,407評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門就轧,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人田度,你說我怎么就攤上這事妒御。” “怎么了镇饺?”我有些...
    開封第一講書人閱讀 162,632評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵乎莉,是天一觀的道長。 經(jīng)常有香客問我奸笤,道長惋啃,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,180評(píng)論 1 292
  • 正文 為了忘掉前任监右,我火速辦了婚禮边灭,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘健盒。我一直安慰自己存筏,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,198評(píng)論 6 388
  • 文/花漫 我一把揭開白布味榛。 她就那樣靜靜地躺著椭坚,像睡著了一般。 火紅的嫁衣襯著肌膚如雪搏色。 梳的紋絲不亂的頭發(fā)上善茎,一...
    開封第一講書人閱讀 51,165評(píng)論 1 299
  • 那天,我揣著相機(jī)與錄音频轿,去河邊找鬼垂涯。 笑死烁焙,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的耕赘。 我是一名探鬼主播骄蝇,決...
    沈念sama閱讀 40,052評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼操骡!你這毒婦竟也來了九火?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 38,910評(píng)論 0 274
  • 序言:老撾萬榮一對(duì)情侶失蹤册招,失蹤者是張志新(化名)和其女友劉穎岔激,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體是掰,經(jīng)...
    沈念sama閱讀 45,324評(píng)論 1 310
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡虑鼎,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,542評(píng)論 2 332
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了键痛。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片炫彩。...
    茶點(diǎn)故事閱讀 39,711評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖絮短,靈堂內(nèi)的尸體忽然破棺而出江兢,到底是詐尸還是另有隱情,我是刑警寧澤戚丸,帶...
    沈念sama閱讀 35,424評(píng)論 5 343
  • 正文 年R本政府宣布划址,位于F島的核電站,受9級(jí)特大地震影響限府,放射性物質(zhì)發(fā)生泄漏夺颤。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,017評(píng)論 3 326
  • 文/蒙蒙 一胁勺、第九天 我趴在偏房一處隱蔽的房頂上張望世澜。 院中可真熱鬧,春花似錦署穗、人聲如沸寥裂。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,668評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽封恰。三九已至,卻和暖如春褐啡,著一層夾襖步出監(jiān)牢的瞬間诺舔,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,823評(píng)論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留低飒,地道東北人许昨。 一個(gè)月前我還...
    沈念sama閱讀 47,722評(píng)論 2 368
  • 正文 我出身青樓,卻偏偏與公主長得像褥赊,于是被迫代替她去往敵國和親糕档。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,611評(píng)論 2 353

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

  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 172,077評(píng)論 25 707
  • ¥開啟¥ 【iAPP實(shí)現(xiàn)進(jìn)入界面執(zhí)行逐一顯】 〖2017-08-25 15:22:14〗 《//首先開一個(gè)線程拌喉,因...
    小菜c閱讀 6,401評(píng)論 0 17
  • 寫在前面: 通常的閱讀速度是每分鐘300-400字速那。如果可以使用4分鐘左右的時(shí)間,了解或回顧一本書司光,自然是一件節(jié)約...
    秋人君閱讀 961評(píng)論 0 4
  • 寫在前面的前面 這篇文章是之前在Github Pages上利用Hexo的心得和整理琅坡,Po在之前的主頁上悉患,轉(zhuǎn)到簡(jiǎn)書上...
    whiteplane閱讀 708評(píng)論 0 1
  • 7月6日 貴陽 13-23℃ 醒來就聞到好香好香的雞湯味残家,好溫暖,就和小時(shí)候的感覺一樣的售躁,媽媽常常會(huì)煲雞湯坞淮,滿屋子...
    欣誼閱讀 455評(píng)論 2 3