一、把数据存储到SD卡上
Android 的存储分为两部分,一部分是内部存储空间,ROM,相当于Windows系统下的电脑内置盘,另一部分是外置存储空间,也就是我们说的SD卡,相当于电脑的U盘之类
找到挂载目录
manifest下
AndroidManifest.xmll
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.logindemo"> //获取读写SD卡的权限 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <!-- <activity android:name=".MainActivity">--> <!-- <intent-filter>--> <!-- <action android:name="android.intent.action.MAIN" />--> <!-- <category android:name="android.intent.category.LAUNCHER" />--> <!-- </intent-filter>--> <!-- </activity>--> <activity android:name=".SDcardDemoActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
注意: Android6.0 就是API 23之后。APP需要动态获取权限。需要用代码获取权限,这也是为了用户数据更加安全。
SDcardDemoActivity.java
package com.example.logindemo; import android.Manifest; import android.app.Activity; import android.content.pm.PackageManager; import android.os.Build; import android.os.Bundle; import android.view.View; import android.widget.Button; import androidx.annotation.Nullable; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; public class SDcardDemoActivity extends Activity implements View.OnClickListener { Button mWritedataBtn ; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); //设置布局 setContentView(R.layout.activity_sd_card_layout); /** * 动态获取权限,Android 6.0 新特性,一些保护权限,除了要在AndroidManifest中声明权限,还要使用如下代码动态获取 */ if (Build.VERSION.SDK_INT >= 23) { int REQUEST_CODE_CONTACT = 101; String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE}; //验证是否许可权限 for (String str : permissions) { if (this.checkSelfPermission(str) != PackageManager.PERMISSION_GRANTED) { //申请权限 this.requestPermissions(permissions, REQUEST_CODE_CONTACT); return; } } } mWritedataBtn=this.findViewById(R.id.write_data_2_sdcard_btn); mWritedataBtn.setOnClickListener(this); } @Override public void onClick(View v) { if(v == mWritedataBtn){ //写数据到SD卡上 File filepath = new File("/storage/self/primary"); File file = new File(filepath,"info.txt"); try { FileOutputStream fileOutputStream = new FileOutputStream(file); fileOutputStream.write("helloSDCard".getBytes()); fileOutputStream.close(); }catch (Exception e){ e.printStackTrace(); } } } }
activity_sd_card_layout.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:gravity="center" android:layout_height="match_parent"> <TextView android:layout_width="wrap_content" android:text="SD卡例子" android:textSize="50dp" android:layout_height="wrap_content"/> <Button android:id="@+id/write_data_2_sdcard_btn" android:layout_width="match_parent" android:text="向SD卡添加内容" android:layout_height="wrap_content"> </Button> </LinearLayout>
获取权限
困扰了我几个小时,就是因为我一开始在文件写入内容时加了个逗号。。。。。。
二、SD卡的获取路径及判断SD卡是否挂载
//获取路径 File externalStorageDirectory=Environment.getExternalStorageDirectory();
else if(v ==mCheckSDcardBtn){ //点击是否存在SD卡 String state = Environment.getExternalStorageState(); if (state.equals(Environment.MEDIA_MOUNTED)) { Log.d(TAG,"SD卡已经挂载"); }else if(state.equals(Environment.MEDIA_REMOVED)){ Log.d(TAG,"SD卡已经删除了"); } }
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:gravity="center" android:layout_height="match_parent"> <TextView android:layout_width="wrap_content" android:text="SD卡例子" android:textSize="50dp" android:layout_height="wrap_content"/> <Button android:id="@+id/write_data_2_sdcard_btn" android:layout_width="match_parent" android:text="向SD卡添加内容" android:layout_height="wrap_content"> </Button> <Button android:layout_width="match_parent" android:text="检查是否存在SD卡" android:id="@+id/sd_card_check_btn" android:layout_height="wrap_content"> </Button> </LinearLayout>
三、获取SD卡的信息
SDcardDemoActivity.java
package com.example.logindemo; import android.Manifest; import android.app.Activity; import android.content.pm.PackageManager; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.text.format.Formatter; import android.util.Log; import android.view.View; import android.widget.Button; import androidx.annotation.Nullable; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.text.Format; public class SDcardDemoActivity extends Activity implements View.OnClickListener { Button mWritedataBtn ; Button mCheckSDcardBtn; Button mGetFreeSizeBtn; private static String TAG="SDcardDemoActivity"; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); //设置布局 setContentView(R.layout.activity_sd_card_layout); /** * 动态获取权限,Android 6.0 新特性,一些保护权限,除了要在AndroidManifest中声明权限,还要使用如下代码动态获取 */ if (Build.VERSION.SDK_INT >= 23) { int REQUEST_CODE_CONTACT = 101; String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE}; //验证是否许可权限 for (String str : permissions) { if (this.checkSelfPermission(str) != PackageManager.PERMISSION_GRANTED) { //申请权限 this.requestPermissions(permissions, REQUEST_CODE_CONTACT); return; } } } //初始化控件 initView(); //创建监听方法 initListener(); } private void initListener() { mWritedataBtn.setOnClickListener(this); mCheckSDcardBtn.setOnClickListener(this); mGetFreeSizeBtn.setOnClickListener(this); } private void initView() { mWritedataBtn=this.findViewById(R.id.write_data_2_sdcard_btn); mCheckSDcardBtn=this.findViewById(R.id.sd_card_check_btn); mGetFreeSizeBtn=this.findViewById(R.id.get_sd_card_free_size_btn); } @Override public void onClick(View v) { //获取路径 File exFile=Environment.getExternalStorageDirectory(); Log.d(TAG,"Ext-file-path"+exFile); if(v == mWritedataBtn){ //写数据到SD卡上 File file = new File(exFile,"info.txt"); try { FileOutputStream fileOutputStream = new FileOutputStream(file); fileOutputStream.write("helloSDCard".getBytes()); fileOutputStream.close(); }catch (Exception e){ e.printStackTrace(); } }else if(v ==mCheckSDcardBtn){ //点击是否存在SD卡 String state = Environment.getExternalStorageState(); if (state.equals(Environment.MEDIA_MOUNTED)) { Log.d(TAG,"SD卡已经挂载"); }else if(state.equals(Environment.MEDIA_REMOVED)){ Log.d(TAG,"SD卡已经删除了"); } }else if(v ==mGetFreeSizeBtn){ //获取剩余空间 long freeSpace = exFile.getFreeSpace(); //把long类型转化为直观的大小 String sizeText = Formatter.formatFileSize(this, freeSpace); Log.d(TAG,"剩余空间"+sizeText); } } }
activity_sd_card_layout.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:gravity="center" android:layout_height="match_parent"> <TextView android:layout_width="wrap_content" android:text="SD卡例子" android:textSize="50dp" android:layout_height="wrap_content"/> <Button android:id="@+id/write_data_2_sdcard_btn" android:layout_width="match_parent" android:text="向SD卡添加内容" android:layout_height="wrap_content"> </Button> <Button android:layout_width="match_parent" android:text="检查是否存在SD卡" android:id="@+id/sd_card_check_btn" android:layout_height="wrap_content"> </Button> <Button android:layout_width="match_parent" android:text="获取SD卡所用空间" android:id="@+id/get_sd_card_free_size_btn" android:layout_height="wrap_content"> </Button> </LinearLayout>