1. 程式人生 > >Android SD資料儲存

Android SD資料儲存

一、新增許可權

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.yxp.sd" >

    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>



    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

二、修改佈局檔案

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

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/label_01"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="name"
            android:textSize="20dp" />

        <EditText
            android:id="@+id/filename"
            android:layout_width="160dp"
            android:layout_height="wrap_content"
            android:layout_alignTop="@id/label_01"
            android:layout_toRightOf="@id/label_01" />
    </RelativeLayout>

    <TextView
        android:id="@+id/label_02"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="label" />


    <EditText
        android:id="@+id/content"
        android:layout_width="fill_parent"
        android:layout_height="120px"
        android:ems="10" >

        <requestFocus />
    </EditText>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/savebutton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="right"
            android:text="save" />

        <Button
            android:id="@+id/readbutton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="right"
            android:text="read" />
    </LinearLayout>

    <TextView
        android:id="@+id/textcontent"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0.10" />

</LinearLayout>

三、修改MainActivity檔案

package com.example.yxp.sd;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;





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


import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.os.Build;


public class MainActivity extends Activity {



    private  EditText filename;
    private  EditText context;
    private TextView textcontent;
    private static final String TAG="simplefile";

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


        filename=(EditText)this.findViewById(R.id.filename);
        context=(EditText)this.findViewById(R.id.content);
        textcontent=(TextView)this.findViewById(R.id.textcontent);
        Button savebtn=(Button)this.findViewById(R.id.savebutton);
        Button viewbtn=(Button)this.findViewById(R.id.readbutton);
        savebtn.setOnClickListener(l);
        viewbtn.setOnClickListener(l);




    }
    private View.OnClickListener l =new OnClickListener() {
        public void onClick(View v) {

            Button button =(Button)v;
            //過濾掉開頭結尾的空格
            String namestr = filename.getText().toString().trim();
            String contentstr =context.getText().toString();

            switch ( button.getId() ) {
                case R.id.savebutton:
                    String resid_s ="success";
                    OutputStream fileos = null;
                    try {
                        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
                        {
                            FileOutputStream outstream = new FileOutputStream("/sdcard/"+namestr+".txt");
                            outstream.write(contentstr.getBytes() );
                            outstream.close();
                        }
                        else
                            return ;
                    } catch (Exception e) {
                        resid_s = "faile";
                        e.printStackTrace();
                    }
                    Toast.makeText(MainActivity.this,  resid_s,Toast.LENGTH_LONG).show();
                    Log.i(TAG, namestr);
                    Log.i(TAG, contentstr);
                    break;
                case R.id.readbutton:
                    String resid_v ="success";
                    InputStream filsIs= null;
                    String contentst = null;
                    try {
                        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
                        {
                            File SDCardDir=Environment.getExternalStorageDirectory();
                            File saveFile = new File(SDCardDir,namestr+".txt");
                            FileInputStream instream = new FileInputStream(saveFile);
                            ByteArrayOutputStream Ostream = new ByteArrayOutputStream();

                            byte[] buffer = new byte[1024];
                            int len = -1;
                            while( (len = instream.read(buffer)) != -1 )
                            {
                                Ostream.write(buffer,0,len);
                            }
                            contentst = Ostream.toString();
                            Ostream.close();
                            instream.close();
                        }
                        else
                        {
                            Toast.makeText(MainActivity.this, "SD卡不存在", Toast.LENGTH_LONG).show();
                        }

                    } catch (Exception e) {
                        resid_v ="faile";
                        e.printStackTrace();

                    }
                    textcontent.setText( contentst);
                    Log.i(TAG, contentst);
                    Toast.makeText(MainActivity.this, resid_v,Toast.LENGTH_LONG).show();
                    Log.i(TAG,namestr);
                    break;
            }
        }
    };



}

四、效果