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

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

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

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

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

JAVA代碼:

1、Activity類(lèi)代碼:

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是否存在并且可寫(xiě)
                    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不存在或不可寫(xiě)",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類(lèi)代碼:

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 文件名稱(chēng) 文件類(lèi)容
     * @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==>文件名稱(chēng),int操作模式(可看源碼信息)
        //Context.MODE_PRIVATE:為默認(rèn)操作模式,代表該文件是私有數(shù)據(jù),只能被該應(yīng)用訪問(wèn),在該模式下,寫(xiě)入的內(nèi)容會(huì)覆蓋源文件的內(nèi)容;
        //Context.MODE_APPEND:為追加操作模式,代表該文件是私有的,只能夠被該應(yīng)用訪問(wèn),在該模式下,寫(xiě)入的內(nèi)容追加在源文件內(nèi)容的后面;
        ////還有一種追加方式為FileoutputStream中的兩個(gè)參數(shù)(String name,boolean append)其中第二個(gè)參數(shù)決定是否以追加的模式來(lái)寫(xiě)入內(nèi)容;
        //Context.MODE_READABLE:表示當(dāng)前文件能被其他應(yīng)用讀取;
        // Context.MODE_WRITEABLE:表示當(dāng)前文件能被其他應(yīng)用寫(xiě)入;
        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寫(xiě)入數(shù)據(jù)權(quán)限
     * <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
     * @param fileName 文件名稱(chēng)
     * @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)輸入文件名稱(chē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>

效果圖:

這里寫(xiě)圖片描述

希望對(duì)你們有幫助!?。。?!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

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

友情鏈接更多精彩內(nèi)容