android 將數據讀寫到SD卡

 本篇博文實現android將字符串數據保存到SD卡上以及從SD讀數據返回。上代碼:

package com.example.android_file2;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.os.Environment;

public class FileService {


	/**
	 * 保存內容到SDcard
	 * 
	 * @param filename文件名稱
	 * @param info文件內容
	 * @return
	 */
	public static String saveInfoToSDcard(String filename, String info) {
		String result = "false";
		File file = new File(Environment.getExternalStorageDirectory(),
				filename);
		if (Environment.MEDIA_MOUNTED.equals(Environment
				.getExternalStorageState())) {
			try {
				FileOutputStream fileOutputStream = new FileOutputStream(file);
				fileOutputStream.write(info.getBytes());
				result = "true";
				fileOutputStream.close();
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else{
			System.out.println("Environment");
		}
		return result;
	}

	
	
	/**
	 * 讀sd卡上的數據
	 * @param filename
	 * @return
	 */
	public static String getStringFromSdcard(String filename) {
		String result = null;
		// 緩存的流,和磁盤無關,不需要關閉
		ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
		File file = new File(Environment.getExternalStorageDirectory(),
				filename);
		if (Environment.MEDIA_MOUNTED.equals(Environment
				.getExternalStorageState())) {
			try {
				FileInputStream fileInputStream = new FileInputStream(file);
				int len = 0;
				byte[] buffer = new byte[1024];
				while ((len = fileInputStream.read(buffer)) != -1) {
					arrayOutputStream.write(buffer, 0, len);
				}
				fileInputStream.close();
				result = new String(arrayOutputStream.toByteArray());
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return result;
	}
}
上面類中的方法分別實現SD卡上存取數據。

還需要在AndroidMainfest.xml中添加使用權限:  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

這樣就可以實現向SD卡上存取數據了。


發佈了41 篇原創文章 · 獲贊 9 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章