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+"\r\n");
            }
            
            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;
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM