Android 數(shù)據(jù)存儲(chǔ)與訪問(wèn)之——文件存儲(chǔ)讀寫(xiě)

2023-03-31 13:46 更新

本節(jié)引言:

嘿嘿,看到這個(gè)題目,相信部分讀者會(huì)問(wèn),你前面的Fragment寫(xiě)完了嗎?嗯,沒(méi)寫(xiě)完,因?yàn)橄肜樱枰?一點(diǎn)時(shí)間,為了提高效率,所以決定像多線程一樣,并發(fā)的來(lái)寫(xiě)教程,這樣可能可以加快寫(xiě)教程的進(jìn)度, 到現(xiàn)在為止,剛好寫(xiě)了60篇,離完成入門(mén)教程還很遠(yuǎn)呢,而前面也說(shuō)過(guò),想在一個(gè)半到兩個(gè)月之內(nèi)完成 這套教程,今天已經(jīng)9.1號(hào)了,要加吧勁~好的,廢話(huà)就這么多,本節(jié)給大家介紹的是Android數(shù)據(jù)存儲(chǔ)與 訪問(wèn)方式中的一個(gè)——文件存儲(chǔ)與讀寫(xiě),當(dāng)然除了這種方式外,我們可以存到SharedPreference,數(shù)據(jù)庫(kù), 或者Application中,當(dāng)然這些后面都會(huì)講,嗯,開(kāi)始本節(jié)內(nèi)容~


1.Android文件的操作模式

學(xué)過(guò)Java的同學(xué)都知道,我們新建文件,然后就可以寫(xiě)入數(shù)據(jù)了,但是Android卻不一樣,因?yàn)锳ndroid是 基于Linux的,我們?cè)谧x寫(xiě)文件的時(shí)候,還需加上文件的操作模式,Android中的操作模式如下:


2.文件的相關(guān)操作方法


嘿嘿,果然讀寫(xiě)SD卡成功~接下來(lái)我們來(lái)看下代碼是怎么寫(xiě)的:

代碼實(shí)現(xiàn):

main_activity.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.jay.example.filedemo2.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="清輸入文件名" />

    <EditText
        android:id="@+id/edittitle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="文件名" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="清輸入文件內(nèi)容" />

    <EditText
        android:id="@+id/editdetail"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="文件內(nèi)容" />

    <Button
        android:id="@+id/btnsave"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="保存到SD卡" />

    <Button
        android:id="@+id/btnclean"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="清空" />

    <Button
        android:id="@+id/btnread"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="讀取sd卡中的文件" />

</LinearLayout>

接著我們來(lái)寫(xiě)一個(gè)SD操作類(lèi): SDFileHelper.java

/**
 * Created by Jay on 2015/9/1 0001.
 */
public class SDFileHelper {

    private Context context;

    public SDFileHelper() {
    }

    public SDFileHelper(Context context) {
        super();
        this.context = context;
    }

    //往SD卡寫(xiě)入文件的方法
    public void savaFileToSD(String filename, String filecontent) throws Exception {
        //如果手機(jī)已插入sd卡,且app具有讀寫(xiě)sd卡的權(quán)限
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            filename = Environment.getExternalStorageDirectory().getCanonicalPath() + "/" + filename;
            //這里就不要用openFileOutput了,那個(gè)是往手機(jī)內(nèi)存中寫(xiě)數(shù)據(jù)的
            FileOutputStream output = new FileOutputStream(filename);
            output.write(filecontent.getBytes());
            //將String字符串以字節(jié)流的形式寫(xiě)入到輸出流中
            output.close();
            //關(guān)閉輸出流
        } else Toast.makeText(context, "SD卡不存在或者不可讀寫(xiě)", Toast.LENGTH_SHORT).show();
    }

    //讀取SD卡中文件的方法
    //定義讀取文件的方法:
    public String readFromSD(String filename) throws IOException {
        StringBuilder sb = new StringBuilder("");
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            filename = Environment.getExternalStorageDirectory().getCanonicalPath() + "/" + filename;
            //打開(kāi)文件輸入流
            FileInputStream input = new FileInputStream(filename);
            byte[] temp = new byte[1024];

            int len = 0;
            //讀取文件內(nèi)容:
            while ((len = input.read(temp)) > 0) {
                sb.append(new String(temp, 0, len));
            }
            //關(guān)閉輸入流
            input.close();
        }
        return sb.toString();
    }

}

接著MainActivity.java實(shí)現(xiàn)相關(guān)邏輯:

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    private EditText editname;
    private EditText editdetail;
    private Button btnsave;
    private Button btnclean;
    private Button btnread;
    private Context mContext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext = getApplicationContext();
        bindViews();
    }

    private void bindViews() {
        editname = (EditText) findViewById(R.id.edittitle);
        editdetail = (EditText) findViewById(R.id.editdetail);
        btnsave = (Button) findViewById(R.id.btnsave);
        btnclean = (Button) findViewById(R.id.btnclean);
        btnread = (Button) findViewById(R.id.btnread);

        btnsave.setOnClickListener(this);
        btnclean.setOnClickListener(this);
        btnread.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btnclean:
                editdetail.setText("");
                editname.setText("");
                break;
            case R.id.btnsave:
                String filename = editname.getText().toString();
                String filedetail = editdetail.getText().toString();
                SDFileHelper sdHelper = new SDFileHelper(mContext);
                try
                {
                    sdHelper.savaFileToSD(filename, filedetail);
                    Toast.makeText(getApplicationContext(), "數(shù)據(jù)寫(xiě)入成功", Toast.LENGTH_SHORT).show();
                }
                catch(Exception e){
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(), "數(shù)據(jù)寫(xiě)入失敗", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.btnread:
                String detail = "";
                SDFileHelper sdHelper2 = new SDFileHelper(mContext);
                try
                {
                    String filename2 = editname.getText().toString();
                    detail = sdHelper2.readFromSD(filename2);
                }
                catch(IOException e){e.printStackTrace();}
                Toast.makeText(getApplicationContext(), detail, Toast.LENGTH_SHORT).show();
                break;
        }
    }
}

最后別忘記在AndroidManifest.xml寫(xiě)上讀寫(xiě)SD卡的權(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"/>

5.關(guān)于原生模擬器SD卡的問(wèn)題

如果是真機(jī)調(diào)試的話(huà)通常都是可以的,對(duì)于原生虛擬機(jī)的話(huà)就問(wèn)題多多了,再我們前面使用 Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)可能 一直返回的是false,就是SD卡不存在,這個(gè)是主要的問(wèn)題,現(xiàn)在新版本的SDK都會(huì)在 創(chuàng)建AVD的時(shí)候會(huì)同時(shí)申請(qǐng)一塊SD卡的存儲(chǔ)區(qū)域的

對(duì)于舊版本的sdk或者其他原因可能需要手動(dòng)關(guān)聯(lián)下sd卡,設(shè)置如下:
①找到創(chuàng)建好的avd的鏡像的路徑:
點(diǎn)擊打開(kāi)avd界面,點(diǎn)擊detail,查看avd鏡像的目錄下


以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)