zoukankan      html  css  js  c++  java
  • 9.Android-读写SD卡案例

    1.效果如下所示:

    2.读写SD卡时,需要给APP添加读写外部存储设备权限,修改AndroidManifest.xml,添加:

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

    如下图所示:

    3.读写SD卡需要用到的Environment类

    Environment类是一个提供访问环境变量的类.

    Environment类常用的方法有:

    static File getRootDirectory();  //获取根目录,默认位于:/system
    static File getDataDirectory();  //获取data目录,默认位于:/data
    static File getDownloadCacheDirectory();  //获取下载文件的缓存目录,默认位于:/cache
    
     
    static String getExternalStorageState();    
    //获取sd卡外部的状态,返回的内容可以判断sd卡是否被挂载.比如:
    //判断if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))、除了MEDIA_MOUNTED("mounted")外,
    //还可以通过MEDIA_MOUNTED_READ_ONLY("mounted_ro")来判断是否是只读挂载。
    static File getExternalStoragePublicDirectory(String type); //获取sd卡指定的type标准目录 //type可以填入: //DIRECTORY_ALARMS 系统提醒铃声存放的标准目录。 //DIRECTORY_DCIM 相机拍摄照片和视频的标准目录。 //DIRECTORY_DOWNLOADS 下载的标准目录。 //DIRECTORY_MOVIES 电影存放的标准目录。 //DIRECTORY_MUSIC 音乐存放的标准目录。 //DIRECTORY_NOTIFICATIONS 系统通知铃声存放的标准目录。 //DIRECTORY_PICTURES 图片存放的标准目录 //DIRECTORY_PODCASTS 系统广播存放的标准目录。 //DIRECTORY_RINGTONES 系统铃声存放的标准目录。 static File getExternalStorageDirectory(); //获取sd卡的路径

    示例如下:

            Log.d("MainActivity", Environment.getExternalStorageState());
    
            Log.d("MainActivity", "getRootDirectory:  "+Environment.getRootDirectory().getAbsolutePath().toString());
    
            Log.d("MainActivity", "getDataDirectory:  "+Environment.getDataDirectory().getAbsolutePath().toString());
    
            Log.d("MainActivity", "getDownloadCacheDirectory:  "+Environment.getDownloadCacheDirectory().getAbsolutePath().toString());
    
            Log.d("MainActivity", "getExternalStorageDirectory:  "+Environment.getExternalStorageDirectory().getAbsolutePath().toString());
    
            Log.d("MainActivity", "DIRECTORY_ALARMS:  "+Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_ALARMS).getAbsolutePath().toString());
    
            Log.d("MainActivity", "DIRECTORY_DCIM:  "+Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath().toString());
    
            Log.d("MainActivity", "DIRECTORY_DOWNLOADS: "+Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath().toString());

    打印:

     4.写activity_main.xml

    <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" >
    
        <TextView
            android:id="@+id/text_label"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="SD卡读写内容:" />
    
        <EditText
            android:id="@+id/et_content"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/text_label"
            android:minLines="5" />
        
        
       <Button 
           android:id="@+id/btn_read"
           android:layout_below="@id/et_content"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:text="读取内容"  />
       
        <Button 
           android:id="@+id/btn_write"
           android:layout_below="@id/et_content"
           android:layout_alignParentRight="true"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:text="写入内容"
           />
        
        <TextView
            android:id="@+id/text_sdSize"
            android:layout_alignParentBottom="true"
            android:layout_centerHorizontal="true"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            
            android:text="SD卡剩余:1KB 总:100KB" />
        
    </RelativeLayout>

    5.写Utils类(用于读写SD卡下的info.txt)

    package com.example.utils;
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import android.annotation.SuppressLint;
    import android.content.Context;
    import android.os.Environment;
    import android.text.format.Formatter;
    import android.util.Log;
    
    public class Utils {
        //获取SD卡下的info.txt内容
        static public String getSDCardInfo(){
          
            if(!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
                return null;
            
            File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/info.txt");  //打开要读的文件
            
            if(!file.exists())        //文件不存在的情况下
            {
                Log.v("sdcard", "file is Empty");
                return "";
            }
            try {
                FileInputStream  fis = new FileInputStream(file);
                BufferedReader br = new BufferedReader(new InputStreamReader(fis));
                StringBuilder sb = new StringBuilder();
                String line = null;
                
                while((line=br.readLine())!=null)        //获取每一行数据源
                {
                    sb.append(line+"
    ");
                }
                
                return sb.toString();
                
            } catch (IOException e) {
                
                e.printStackTrace();
                
                return null;
            }
        }
        
        //将content写入SD卡下的info.txt
        static public boolean writeSDCardInfo(String content){
        
            if(!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
                return false;
            
            File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/info.txt");    
        
            try {
                FileOutputStream fos = new FileOutputStream(file);
                fos.write(content.getBytes());
                fos.flush();
                fos.close();
                return true;
                
            } catch (IOException e) {
                
                e.printStackTrace();
                return false;
            }
        }
    }

    6.写MainActivity类

    package com.example.sdreadWrite;
    import java.io.File;
    import com.example.utils.Utils;
    import android.os.Bundle;
    import android.os.Environment;
    import android.app.Activity;
    import android.text.format.Formatter;
    import android.view.Menu;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.TextView;
    import android.widget.Toast;
    
    public class MainActivity extends Activity {
    
        private TextView text_sdSize;
        private EditText et_content;
    
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            
            et_content = (EditText)findViewById(R.id.et_content);
            text_sdSize = (TextView)findViewById(R.id.text_sdSize);
           
            //获取SD卡容量
            if(!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
                
                text_sdSize.setText("未挂载SD卡,获取SD卡容量失败");
                
            }else{
                
                File externalStorageDirectory = Environment.getExternalStorageDirectory();
                
                long totalSpace = externalStorageDirectory.getTotalSpace();
                long freeSpace = externalStorageDirectory.getFreeSpace();
                
                String totalSize = Formatter.formatFileSize(MainActivity.this, totalSpace);
    
                String freeSize = Formatter.formatFileSize(MainActivity.this, freeSpace);
                
                text_sdSize.setText("SD卡剩余:"+ freeSize+"  总:"+totalSize);
            }
            
            Button btn_read = (Button)findViewById(R.id.btn_read);
            //读取SD卡事件
            btn_read.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    
                    String content = Utils.getSDCardInfo();
                    
                    if(content==null){
                        
                        Toast.makeText(MainActivity.this,"读取失败",Toast.LENGTH_SHORT).show();
                        
                    }else{
                        et_content.setText(content);
                        Toast.makeText(MainActivity.this,"读取成功",Toast.LENGTH_SHORT).show();
                    }
                }
            });
            
            
            Button btn_write = (Button)findViewById(R.id.btn_write);
            //写入sd卡事件
            btn_write.setOnClickListener(new OnClickListener() {
                
                @Override
                public void onClick(View v) {
                    
                    if(Utils.writeSDCardInfo(et_content.getText().toString())){
                            
                        Toast.makeText(MainActivity.this,"写入成功",Toast.LENGTH_SHORT).show();
                        
                    }else{
                        
                        Toast.makeText(MainActivity.this,"写入失败",Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }
    
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.main, menu);
            return true;
        }
    }
  • 相关阅读:
    python增加 删除列表元素
    Fildder2
    Appscan使用第三方浏览器
    Appscan的下载安装
    http状态码
    python学习资料
    Fiddler抓包工具
    性能测试的一些资料
    Jmeter分布式测试
    内存溢出的原因及解决办法(转)
  • 原文地址:https://www.cnblogs.com/lifexy/p/12167457.html
Copyright © 2011-2022 走看看