Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> Android編程入門 >> andorid 手機外部儲存操作

andorid 手機外部儲存操作

編輯:Android編程入門

.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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.hanqi.application3.DataActivity1"
    android:orientation="vertical">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/et_1"
        android:hint="Key"/>
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/et_2"
        android:hint="Value"/>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:text="保存"
            android:layout_weight="1"
            android:onClick="bt1_onClick"/>
        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:text="讀取"
            android:layout_weight="1"
            android:onClick="bt2_onClick"/>

    </LinearLayout>
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/et_3"
        android:hint="要保存的內容"/>
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/et_4"
        android:hint="從文件中讀取的內容"/>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:text="保存"
            android:layout_weight="1"
            android:onClick="bt3_onClick"/>
        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:text="讀取"
            android:layout_weight="1"
            android:onClick="bt4_onClick"/>

    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:text="保存文件"
            android:layout_weight="1"
            android:onClick="bt5_onClick"/>
        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:text="讀取文件"
            android:layout_weight="1"
            android:onClick="bt6_onClick"/>

    </LinearLayout>

    <ImageView
        android:layout_width="80dp"
        android:layout_height="80dp"
        android:src="@drawable/da1"
        android:id="@+id/iv_4"
        android:visibility="gone"/>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="保存到帶包名的目錄"
        android:layout_weight="1"
        android:onClick="bt7_onClick"/>
    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="從帶包名目錄讀取"
        android:layout_weight="1"
        android:onClick="bt8_onClick"/>
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="保存到自定義目錄"
        android:layout_weight="1"
        android:onClick="bt9_onClick"/>
    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="從自定義目錄讀取"
        android:layout_weight="1"
        android:onClick="bt10_onClick"/>
    </LinearLayout>

</LinearLayout>

.java   9和10

package com.hanqi.application3;

import android.content.SharedPreferences;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.PrintStream;


public class DataActivity1 extends AppCompatActivity {
    EditText et1;
    EditText et2;
    EditText et3;
    EditText et4;

    ImageView iv4;
    SharedPreferences sp;

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

        et1=(EditText)findViewById(R.id.et_1);
        et2=(EditText)findViewById(R.id.et_2);

        et3=(EditText)findViewById(R.id.et_3);
        et4=(EditText)findViewById(R.id.et_4);
        iv4= (ImageView)findViewById(R.id.iv_4);
        //1.獲取sp的實例,制定了文件名和操作模式   MODE_PRIVATE私有
        sp = getSharedPreferences("mydata",MODE_PRIVATE);

    }
    //操作assets內的文件
    public void bt5_onClick(View v)
    {
        //1.獲取AssetManager
        AssetManager am = getAssets();

         try{
             //2.打開文件,獲取輸入流
             InputStream is = am.open("denglu.jpg");
             //3.獲取輸出流
             FileOutputStream fos2 = openFileOutput("denglu2.jpg",MODE_PRIVATE);
             //4.邊度編寫
             byte[] bb2 = new byte[1024];

             int ii2 = 0;
             while ((ii2 = is.read(bb2))>0)
             {
                 fos2.write(bb2,0,ii2);
             }

             fos2.close();

             is.close();

             Toast.makeText(DataActivity1.this, "保存成功", Toast.LENGTH_SHORT).show();


         }
         catch (Exception e)
         {
             e.printStackTrace();
             Toast.makeText(DataActivity1.this, "保存失敗", Toast.LENGTH_SHORT).show();
         }
    }
    //從手機內部存儲讀圖片文件
    public void bt6_onClick(View v)
    {
        //改變ImageView的圖片來源,指向手機存儲空間

        //1.獲取文件存儲的絕對路徑
        String filepath = getFilesDir().getAbsolutePath();
        //2.組合完整路徑
        filepath += "/denglu2.jpg";
        //3.生成位圖實例
        Bitmap bm2 = BitmapFactory.decodeFile(filepath);
        //4.改變ImageView的圖片來源
        iv4.setImageBitmap(bm2);

    }
    //文件名
    final String FILENAME = "test.txt";

    public void bt3_onClick(View v)
    {
        //1.獲取要存儲的內容
        String content = et3.getText().toString();
        //2.獲取輸出流
        try {
            FileOutputStream fos1 = openFileOutput(FILENAME, MODE_APPEND);
            //3.構造一個打印輸出流
            PrintStream pm1 = new PrintStream(fos1);
            //4.寫入內容
            pm1.println(content);

            pm1.close();

            fos1.close();

            Toast.makeText(DataActivity1.this, "保存成功", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            e.printStackTrace();

            Toast.makeText(DataActivity1.this, "保存失敗", Toast.LENGTH_SHORT).show();
        }


    }

    public void bt4_onClick(View v)
    {
        try {
        //1.獲取輸入流
            FileInputStream fis1 = openFileInput(FILENAME);
            //2.定義讀取的數組
            byte[] bt11 = new byte[1024];
            //3.讀出數據的長度

            int ii = 0;

            StringBuilder  bb1 = new StringBuilder ();
            while ((ii = fis1.read(bt11))>0)
            {
                bb1.append(new String(bt11,0, ii));
            }

            fis1.close();
            //設置顯示讀出的內容
            et4.setText(bb1);

            Toast.makeText(DataActivity1.this, "顯示成功", Toast.LENGTH_SHORT).show();
        }
        catch (Exception e)
        {
            e.printStackTrace();

            Toast.makeText(DataActivity1.this, "保存失敗", Toast.LENGTH_SHORT).show();

        }

    }

    //保存
    public void bt1_onClick(View v)
    {
        //1.獲取Key和Value
        String key = et1.getText().toString();
        String value = et2.getText().toString();
        if (key.length() ==0||value.length() == 0)
        {
            Toast.makeText(DataActivity1.this, "key或value不能為空", Toast.LENGTH_SHORT).show();
        }
        else {



        //2.取得Editor        edit編輯器
        SharedPreferences.Editor editor = sp.edit();
        //3.放入鍵值對
        editor.putString(key,value);
        //4.提交保存
        boolean b = editor.commit();
        if (b)
        {
            Toast.makeText(DataActivity1.this, "保存成功", Toast.LENGTH_SHORT).show();
        }
        else
        {
            Toast.makeText(DataActivity1.this, "保存失敗", Toast.LENGTH_SHORT).show();
        }
        }

    }
    //讀取
    public void bt2_onClick(View v)
    {

        //1.獲取要讀的key
        String key = et1.getText().toString();
        //2.讀並設置文本框
        et2.setText(sp.getString(key,"沒有發現key"));

    }

    //向外部存儲空間存儲文件  保存到帶包名的目錄
    public void bt7_onClick(View v)
    {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {

            //1.獲取要存儲的內容
            String content = et3.getText().toString();
            //2.獲取外部帶包名的目錄
            //String sdPath = Environment.getExternalStorageDirectory().getAbsolutePath();
            //Toast.makeText(DataActivity1.this, "sdPath= "+sdPath, Toast.LENGTH_SHORT).show();
            //參數  代表不同文件類型的子目錄,如果沒有,就傳null
            String sdPath = getExternalFilesDir(null).getAbsolutePath();
            Toast.makeText(DataActivity1.this, "sdPath = "+sdPath, Toast.LENGTH_SHORT).show();
            //3.構造輸出流
            sdPath += "/" +FILENAME;
            try {
                FileOutputStream fos3 = new FileOutputStream(sdPath);

                //傳統方式  字節數組方式

                fos3.write(content.getBytes("utf-8"));

                fos3.close();

                Toast.makeText(DataActivity1.this, "保存成功", Toast.LENGTH_SHORT).show();

            }
            catch (Exception e)
            {
                e.printStackTrace();
                Toast.makeText(DataActivity1.this, "保存失敗", Toast.LENGTH_SHORT).show();

            }

        }
        else
        {
            Toast.makeText(DataActivity1.this, "SD卡沒有掛載", Toast.LENGTH_SHORT).show();
        }







    }

    //從外部存儲空間讀取文件   帶包名的目錄
    public void bt8_onClick(View v) {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {

            //1.獲取要存儲的內容
            //String content = et3.getText().toString();
            //2.獲取外部帶包名的目錄
            //String sdPath = Environment.getExternalStorageDirectory().getAbsolutePath();
            //Toast.makeText(DataActivity1.this, "sdPath= "+sdPath, Toast.LENGTH_SHORT).show();
            //參數  代表不同文件類型的子目錄,如果沒有,就傳null
            String sdPath = getExternalFilesDir(null).getAbsolutePath();
            //Toast.makeText(DataActivity1.this, "sdPath = "+sdPath, Toast.LENGTH_SHORT).show();
            //3.構造輸入流
            sdPath += "/" + FILENAME;
            try {
                FileInputStream fis3 = new FileInputStream(sdPath);

                byte[] b = new byte[1024];
                int i = 0;
                StringBuilder sb1 = new StringBuilder();

                while ((i = fis3.read(b)) > 0) {
                    sb1.append(new String(b, 0, i));
                }

                et4.setText(sb1);


                Toast.makeText(DataActivity1.this, "讀取成功", Toast.LENGTH_SHORT).show();

            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(DataActivity1.this, "讀取失敗", Toast.LENGTH_SHORT).show();

            }

        } else {
            Toast.makeText(DataActivity1.this, "SD卡沒有掛載", Toast.LENGTH_SHORT).show();
        }


    }
    //向外部存儲空間存儲文件   保存到自定義的目錄
    public void bt9_onClick(View v)
    {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {

            //1.獲取要存儲的內容
            String content = et3.getText().toString();
            //2.獲取外部存儲的根目錄
            String sdPath = Environment.getExternalStorageDirectory().getAbsolutePath();
            //在sd卡的根目錄下,創建子目錄
            sdPath += "/hanqi";
            //實例化File  指向一個目錄
            File file = new File(sdPath);
            //如果不存在
            if(!file.exists())
            {
                //創建目錄
                file.mkdirs();
            }

            Toast.makeText(DataActivity1.this, "sdPath= "+sdPath, Toast.LENGTH_SHORT).show();

            //3.構造輸出流
            sdPath += "/" +FILENAME;
            try {
                FileOutputStream fos3 = new FileOutputStream(sdPath);

                //傳統方式  字節數組方式

                fos3.write(content.getBytes("utf-8"));

                fos3.close();

                Toast.makeText(DataActivity1.this, "保存成功", Toast.LENGTH_SHORT).show();

            }
            catch (Exception e)
            {
                e.printStackTrace();
                Toast.makeText(DataActivity1.this, "保存失敗", Toast.LENGTH_SHORT).show();

            }

        }
        else
        {
            Toast.makeText(DataActivity1.this, "SD卡沒有掛載", Toast.LENGTH_SHORT).show();
        }







    }

    //從外部存儲空間讀取文件   帶包名的目錄
    public void bt10_onClick(View v) {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {

            //1.獲取要存儲的內容
            //String content = et3.getText().toString();
            //2.獲取外部帶包名的目錄
            String sdPath = Environment.getExternalStorageDirectory().getAbsolutePath();
            //Toast.makeText(DataActivity1.this, "sdPath= "+sdPath, Toast.LENGTH_SHORT).show();
            //參數  代表不同文件類型的子目錄,如果沒有,就傳null
            //String sdPath = getExternalFilesDir(null).getAbsolutePath();
            //Toast.makeText(DataActivity1.this, "sdPath = "+sdPath, Toast.LENGTH_SHORT).show();
            //3.構造輸入流
            sdPath += "/hanqi"+"/" + FILENAME;
            try {
                FileInputStream fis3 = new FileInputStream(sdPath);

                byte[] b = new byte[1024];
                int i = 0;
                StringBuilder sb1 = new StringBuilder();

                while ((i = fis3.read(b)) > 0) {
                    sb1.append(new String(b, 0, i));
                }

                et4.setText(sb1);


                Toast.makeText(DataActivity1.this, "讀取成功", Toast.LENGTH_SHORT).show();

            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(DataActivity1.this, "讀取失敗", Toast.LENGTH_SHORT).show();

            }

        } else {
            Toast.makeText(DataActivity1.this, "SD卡沒有掛載", Toast.LENGTH_SHORT).show();
        }


    }
}

 

<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
權限
  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved