1. 由於寫入資料到SD卡是有需要額外的權限,因此需在AndroidManifest.xml允許存取android.permission.WRITE_EXTERNAL_STORAGE這個權限。

2.AccessSDCardExample.java

01.package tw.nicky;
02.import java.io.File;
03.import java.io.FileWriter;
04.import java.io.IOException;
05.import android.app.Activity;
06.import android.os.Bundle;
07.import android.os.Environment;
08. 
09.public class AccessSDCardExample extends Activity {
10. 
11. @Override
12.    public void onCreate(Bundle savedInstanceState) {
13.        super.onCreate(savedInstanceState);
14.        setContentView(R.layout.main);
15.         
16.        //判斷SD卡是否存在
17.        if(!Environment.getExternalStorageState().equals(Environment.MEDIA_REMOVED) ){
18.            try {
19.             //取得SD卡路徑
20.                File SDCardpath = Environment.getExternalStorageDirectory();
21.                File myDataPath = new File( SDCardpath.getAbsolutePath() + "/myData" );
22.                if( !myDataPath.exists() ) myDataPath.mkdirs();
23.                //將資料寫入到SD卡
24.                FileWriter myFile = new FileWriter( SDCardpath.getAbsolutePath() +"/myData/test.txt" );
25.                myFile.write("This is a test.");
26.                myFile.close();
27.   catch (IOException e) {
28.    e.printStackTrace();
29.   }
30.         }
31.    }
32.}


3. AndroidManifest.xml

01.<?xml version="1.0" encoding="utf-8"?>
02.<manifest xmlns:android="http://schemas.android.com/apk/res/android"
03.      package="tw.nicky"
04.      android:versionCode="1"
05.      android:versionName="1.0">
06.    <application android:icon="@drawable/icon" android:label="@string/app_name">
07.        <activity android:name=".AccessSDCardExample"
08.                  android:label="@string/app_name">
09.            <intent-filter>
10.                <action android:name="android.intent.action.MAIN" />
11.                <category android:name="android.intent.category.LAUNCHER" />
12.            </intent-filter>
13.        </activity>
14.    </application>
15.    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
16.</manifest>


4. SD卡內容

 

 

arrow
arrow
    全站熱搜

    小犬 發表在 痞客邦 留言(0) 人氣()