码迷,mamicode.com
首页 > 移动开发 > 详细

Android笔记(四十八) Android中的资源访问——SDCard

时间:2015-11-01 01:41:47      阅读:348      评论:0      收藏:0      [点我收藏+]

标签:

访问存储在SD卡中的文件

      使用 Environment.getExternalStorageState(); 判断是否存在内存卡

      使用 Environment.getExternalStorageDirectory() 来获取内存卡的根目录路径

      内存卡写入:

MainActivity.java

package cn.lixyz.iotest.activity;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import cn.lixyz.iotest.R;
import cn.lixyz.iotest.util.IOFile;

public class MainActivity extends Activity implements OnClickListener {

    private Button bt_sdcard_exist, bt_sdcard_write;
    private EditText et_sdcard_input;

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

        findView();
        bt_sdcard_exist.setOnClickListener(this);
        bt_sdcard_write.setOnClickListener(this);
    }

    public void findView() {
        bt_sdcard_exist = (Button) findViewById(R.id.bt_sdcard_exist);
        bt_sdcard_write = (Button) findViewById(R.id.bt_sdcard_write);
        et_sdcard_input = (EditText) findViewById(R.id.et_sdcard_input);
    }

    @Override
    public void onClick(View v) {
        IOFile ioFile;
        switch (v.getId()) {
        case R.id.bt_sdcard_exist:
            ioFile = new IOFile(this);
            ioFile.sdCardExist();
            break;
        case R.id.bt_sdcard_write:
            String inputString = et_sdcard_input.getText().toString();
            ioFile = new IOFile(this);
            ioFile.writeToSDCard(inputString);
            break;

        default:
            break;
        }
    }

}

 

activity_main.xml

<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="cn.lixyz.iotest.activity.MainActivity" >

    <Button
        android:id="@+id/bt_sdcard_exist"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="判断手机是否安装内存卡" />

    <EditText
        android:id="@+id/et_sdcard_input"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="输入您要写入的内容" />

    <Button
        android:id="@+id/bt_sdcard_write"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="SDCard写入" />

</LinearLayout>

 

IOFile.java

package cn.lixyz.iotest.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

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

public class IOFile {

    Context mContext;

    // 在构造函数中创建一个Context参数,用于在非Activity处弹出Toast
    public IOFile(Context context) {
        mContext = context;
    }

    public void sdCardExist() {
        // 判断手机收安装内存卡,如果没有安装,则弹出提示
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            Toast.makeText(mContext, "您没有安装SD卡", Toast.LENGTH_SHORT).show();
        }
    }

    public void writeToSDCard(String str) {

        try {
            // 获取内存卡跟路径
            String sdCardDir = Environment.getExternalStorageDirectory().toString();
            File fileName = new File(sdCardDir + "/" + "fileForSDCard.txt");
            if (!fileName.exists()) {
                fileName.createNewFile();
            }
            
            //写入文件
            FileWriter fileWriter = new FileWriter(fileName);
            fileWriter.write(str);
       fileWriter.flush();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

      这样运行,会提示权限错误:

技术分享

      需要给工程添加权限:

    <!-- 在内存卡中创建文件和删除文件的权限 -->
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
    <!-- 向内存卡写入数据的权限 -->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

      运行结果:

技术分享技术分享

 

      内存卡读取:

MainActivity.java

package cn.lixyz.iotest.activity;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import cn.lixyz.iotest.R;
import cn.lixyz.iotest.util.IOFile;

public class MainActivity extends Activity implements OnClickListener {

    private Button bt_sdcard_exist, bt_sdcard_write, bt_sdcard_read;
    private EditText et_sdcard_input;

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

        findView();
        bt_sdcard_exist.setOnClickListener(this);
        bt_sdcard_write.setOnClickListener(this);
        bt_sdcard_read.setOnClickListener(this);
    }

    public void findView() {
        bt_sdcard_exist = (Button) findViewById(R.id.bt_sdcard_exist);
        bt_sdcard_write = (Button) findViewById(R.id.bt_sdcard_write);
        et_sdcard_input = (EditText) findViewById(R.id.et_sdcard_input);
        bt_sdcard_read = (Button) findViewById(R.id.bt_sdcard_read);
    }

    @Override
    public void onClick(View v) {
        IOFile ioFile;
        switch (v.getId()) {
        case R.id.bt_sdcard_exist:
            ioFile = new IOFile(this);
            ioFile.sdCardExist();
            break;
        case R.id.bt_sdcard_write:
            ioFile = new IOFile(this);
            String inputString = et_sdcard_input.getText().toString();
            ioFile.writeToSDCard(inputString);
            break;
        case R.id.bt_sdcard_read:
            ioFile = new IOFile(this);
            ioFile.readFromSDCard();
            break;
        }
    }

}

 

activity_main.xml

<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="cn.lixyz.iotest.activity.MainActivity" >

    <Button
        android:id="@+id/bt_sdcard_exist"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="判断手机是否安装内存卡" />

    <EditText
        android:id="@+id/et_sdcard_input"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="输入您要写入的内容" />

    <Button
        android:id="@+id/bt_sdcard_write"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="SDCard写入" />

    <Button
        android:id="@+id/bt_sdcard_read"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="SDCard读取" />

</LinearLayout>

 

IOFile.java

package cn.lixyz.iotest.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.Flushable;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import android.content.Context;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;

public class IOFile {

    Context mContext;

    // 在构造函数中创建一个Context参数,用于在非Activity处弹出Toast
    public IOFile(Context context) {
        mContext = context;
    }

    // 判断手机是否安装内存卡
    public void sdCardExist() {
        // 判断手机收安装内存卡,如果没有安装,则弹出提示
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            Toast.makeText(mContext, "您没有安装SD卡", Toast.LENGTH_SHORT).show();
        }
    }

    // 往内存卡中写入内容
    public void writeToSDCard(String str) {
        try {
            // 获取内存卡跟路径
            String sdCardDir = Environment.getExternalStorageDirectory().toString();
            File fileName = new File(sdCardDir + "/" + "fileForSDCard.txt");
            if (!fileName.exists()) {
                fileName.createNewFile();
            }
            // 写入文件
            FileWriter fileWriter = new FileWriter(fileName);
            fileWriter.write(str);
            fileWriter.flush();

        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    // 从内存卡中读取内容
    public void readFromSDCard() {
        try {
            File file = new File(Environment.getExternalStorageDirectory() + "/" + "fileForSDCard.txt");
            FileInputStream fileInputStream = new FileInputStream(file);
            byte[] bytes = new byte[fileInputStream.available()];
            fileInputStream.read(bytes);
            fileInputStream.close();

            String str = new String(bytes);
            Log.d("TTT", "文件内容是:" + str);

        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

 

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="cn.lixyz.iotest"
    android:versionCode="1"
    android:versionName="1.0" >

    <!-- 在内存卡中创建文件和删除文件的权限 -->
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
    <!-- 向内存卡写入数据的权限 -->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    
    <uses-sdk
        android:minSdkVersion="19"
        android:targetSdkVersion="19" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="cn.lixyz.iotest.activity.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>

      运行结果:

技术分享

  

Android笔记(四十八) Android中的资源访问——SDCard

标签:

原文地址:http://www.cnblogs.com/xs104/p/4926611.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!