1. 程式人生 > >把資料儲存到外部SD卡上

把資料儲存到外部SD卡上

一、執行效果圖


二、核心程式碼

package com.example.filepersistencetest;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {
	private Button button;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		button = (Button) this.findViewById(R.id.button);
		button.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				writeSDcard("Hello,恭喜您資料讀取了!");
			}
		});

		if (Environment.MEDIA_MOUNTED.equals(state)) {

			mExternalStorageAvailable = mExternalStorageWriteable = true;
		} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
			// We can only read the media
			mExternalStorageAvailable = true;
			mExternalStorageWriteable = false;
		} else {
			// Something else is wrong. It may be one of many other states, but
			// all we need
			// to know is we can neither read nor write
			mExternalStorageAvailable = mExternalStorageWriteable = false;
		}
	}

	boolean mExternalStorageAvailable = false;
	boolean mExternalStorageWriteable = false;
	String state = Environment.getExternalStorageState();

	// 向SD卡寫入資料
	private void writeSDcard(String str) {
		try {
			// 判斷是否存在SD卡
			if (Environment.getExternalStorageState().equals(
					Environment.MEDIA_MOUNTED)) {
				// 獲取SD卡的目錄
				File sdDire = Environment.getExternalStorageDirectory();
				FileOutputStream outFileStream = new FileOutputStream(
						sdDire.getCanonicalPath() + "/test.txt");
				outFileStream.write(str.getBytes());
				outFileStream.close();
				Toast.makeText(this, "資料儲存到text.txt檔案了", Toast.LENGTH_LONG)
						.show();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 要加許可權<uses-permission
	// android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
	void createExternalStoragePrivateFile() {
		File file = new File(getExternalFilesDir(null), "");
		try {
			InputStream is = getResources()
					.openRawResource((Integer) null);
			OutputStream os = new FileOutputStream(file);
			byte[] data = new byte[is.available()];
			is.read(data);
			os.write(data);
			is.close();
			os.close();
		} catch (IOException e) {
			Log.w("ExternalStorage", "Error writing " + file, e);
		}
	}

	// 要加許可權<uses-permission
	// android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
	void deleteExternalStoragePrivateFile() {
		File file = new File(getExternalFilesDir(null), "");
		if (file != null) {
			file.delete();
		}
	}

	boolean hasExternalStoragePrivateFile() {
		File file = new File(getExternalFilesDir(null), "");
		if (file != null) {
			return file.exists();
		}
		return false;
	}

}
<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/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:text="向SD中寫入資料" />


</RelativeLayout>

三、遇到的問題。
剛開始不知道如何實現向外部sd卡中寫入資料,上網百度,檢視別人的部落格還參考第一行程式碼。最後實現。