Android 数据访问之External Storage 数据保存在sd卡 demo+笔记

使用Activity的openFileOutput()方法保存文件,文件是存放在手机空间上,一般手机的存储空间不是很大,存放些小文件还行,如果要存放像视频这样的大文件,是不可行的。对于像视频这样的大文件,我们可以把它存放在SDCard。 SDCard是干什么的?你可以把它看作是移动硬盘或U盘。
在模拟器中使用SDCard,你需要先创建一张SDCard卡(当然不是真的SDCard,只是镜像文件)。创建SDCard可以在Eclipse创建模拟器时随同创建。
在程序中访问SDCard,你需要申请访问SDCard的权限。
    在AndroidManifest.xml中加入访问SDCard的权限如下:
    <!-- 在SDCard中创建与删除文件权限 -->
    <uses-permission       android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
    <!-- 往SDCard写入数据权限 -->

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


要往SDCard存放文件,程序必须先判断手机是否装有SDCard,并且可以进行读写。
注意:访问SDCard必须在AndroidManifest.xml中加入访问SDCard的权限


    if(Environment.getExternalStorageState().equals(
       Environment.MEDIA_MOUNTED)){
         //获取SDCard目录
         File sdCardDir = Environment.getExternalStorageDirectory();
         File saveFile = new File(sdCardDir, “gem.txt”);
    FileOutputStream outStream = new FileOutputStream(saveFile);
    outStream.write("csdn".getBytes());
    outStream.close();
    }


Environment.getExternalStorageState()方法用于获取SDCard的状态,如果手机装有SDCard,并且可以进行读写,那么方法返回的状态等于Environment.MEDIA_MOUNTED。
Environment.getExternalStorageDirectory()方法用于获取SDCard的目录,当然要获取SDCard的目录,你也可以这样写:
     File sdCardDir = new File("/mnt/sdcard"); //获取SDCard目录
     File saveFile = new File(sdCardDir, "gem.txt"); 
     //上面两句代码可以合成一句: File saveFile = new   File("/mnt/sdcard/csdn.txt");
     注意:早期的版本sd卡目录固定是/mnt/sdcard,现在虚拟机的目录也还是/mnt/sdcard。但是,厂商会二次开发,导致每一款手机的SD卡目录不同


案例

1配置清单文件添加两个permission

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

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />
    <!-- 在SDCard中创建与删除文件权限 -->
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
    <!-- 往SDCard写入数据权限 -->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

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


2编写布局文件 添加两个按钮设置点击事件

<RelativeLayout 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=".MainActivity" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="sd_write"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="sd_write" />

    <Button
        android:id="@+id/button2"
        android:onClick="sd_read"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/button1"
        android:text="sd_read" />

</RelativeLayout>

4实现主界面的点击事件

package com.example.writesdcard;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.view.View;
import android.widget.Toast;


public class MainActivity extends Activity {


<span style="white-space:pre">	</span>@Override
<span style="white-space:pre">	</span>protected void onCreate(Bundle savedInstanceState) {
<span style="white-space:pre">		</span>super.onCreate(savedInstanceState);
<span style="white-space:pre">		</span>setContentView(R.layout.activity_main);
<span style="white-space:pre">	</span>}


<span style="white-space:pre">	</span>public void sd_write(View view) {
<span style="white-space:pre">		</span>// 用来判断sd卡是否存在 Environment.MEDIA_MOUNTED表示sd存在
<span style="white-space:pre">		</span>if (Environment.getExternalStorageState().equals(
<span style="white-space:pre">				</span>Environment.MEDIA_MOUNTED)) {
<span style="white-space:pre">			</span>try {
<span style="white-space:pre">				</span>// 获取SDCard目录 官方sd卡目录/mnt/sdcard 但是手机厂商可能将sd卡改了
<span style="white-space:pre">				</span>File sdCardDir = Environment.getExternalStorageDirectory();
<span style="white-space:pre">				</span>File saveFile = new File(sdCardDir, "csdn.txt");
<span style="white-space:pre">				</span>FileOutputStream outStream = new FileOutputStream(saveFile);
<span style="white-space:pre">				</span>outStream.write("csdn".getBytes());
<span style="white-space:pre">				</span>outStream.close();
<span style="white-space:pre">			</span>} catch (Exception e) {
<span style="white-space:pre">				</span>// TODO Auto-generated catch block
<span style="white-space:pre">				</span>e.printStackTrace();
<span style="white-space:pre">			</span>}
<span style="white-space:pre">		</span>}


<span style="white-space:pre">	</span>}


<span style="white-space:pre">	</span>public void sd_read(View view) {
<span style="white-space:pre">		</span>// 用来判断sd卡是否存在 Environment.MEDIA_MOUNTED表示sd存在
<span style="white-space:pre">		</span>if (Environment.getExternalStorageState().equals(
<span style="white-space:pre">				</span>Environment.MEDIA_MOUNTED)) {
<span style="white-space:pre">			</span>try {
<span style="white-space:pre">				</span>// 获取SDCard目录 官方sd卡目录/mnt/sdcard 但是手机厂商可能将sd卡改了
<span style="white-space:pre">				</span>File sdCardDir = Environment.getExternalStorageDirectory();
<span style="white-space:pre">				</span>File saveFile = new File(sdCardDir, "csdn.txt");
<span style="white-space:pre">				</span>FileInputStream is = new FileInputStream(saveFile);
<span style="white-space:pre">				</span>int len = is.available();
<span style="white-space:pre">				</span>byte[] buffer = new byte[len];
<span style="white-space:pre">				</span>String result = "";
<span style="white-space:pre">				</span>while (is.read(buffer) != -1) {
<span style="white-space:pre">					</span>result += new String(buffer);
<span style="white-space:pre">				</span>}
<span style="white-space:pre">				</span>Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT)
<span style="white-space:pre">						</span>.show();
<span style="white-space:pre">				</span>is.close();
<span style="white-space:pre">			</span>} catch (Exception e) {
<span style="white-space:pre">				</span>// TODO Auto-generated catch block
<span style="white-space:pre">				</span>e.printStackTrace();
<span style="white-space:pre">			</span>}
<span style="white-space:pre">		</span>}
<span style="white-space:pre">	</span>}
}

运行结果:点击sd_write会在虚拟机storage/sdcard/下生成csdn.txt文件 文件内容:csdn(注意:此目录为4.4虚拟机所有,其他版本虚拟机或真机极有可能不保存在该文件夹下)

点击sd_read 会有Toast显示文件内容

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值