安卓存儲數據和文件系列1:讀寫sdCard方式

在android手機存儲數據和文件的方式分爲五種:1.文件存儲(sd卡中)、2.採用共享參數(sharedpreferences)的方式存儲、3.SQLite數據庫存儲、4.使用內容提供者(Content Provider)存儲、5.存放在網絡的服務器端。讀寫sdCard卡是常見的一種操作方式。下面我們來介紹一個這種方式的使用。

整體思路:定義一個FileService類,在這個類中定義一個getFileFromSdcard方法,用於傳一個文件名參數讀取sdCard卡中的文件返回讀取的字符串,定義一個saveContentToSdcard方法,用於傳一個文件名參數和一個字符串參數,來將這個字符串寫入這個文件,並保存於sdCard卡中;創建一個繼承AndroidTestCase的單元測試類MyTest,在這個類中定義saveFile方法,在方法中實例化一個FileService對象,並調用saveContentToSdcard這個方法,將指定字符串寫入對應文件,並存儲於sdCard卡,在這個類中定義另一個方法readFile,在這個方法中實例化一個FileService對象,並調用getFileFromSdcard這個方法,讀取指定的文件,並將該文件中的字符串輸出。注意要在清單文件AndroidManifest.xml文件中加上單元測試和讀寫sdCard卡的授權。

FileService.java文件:

public class FileService {

	private Context context;
	
	public FileService(Context context) {
		this.context=context;
	}
	
	public FileService(){
		
	}
	
	public String getFileFromSdcard(String fileName){
		FileInputStream inputStream=null;
//		緩存的流,與磁盤無關,不需要關閉,會寫在緩衝區裏面
		ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
		File file=new File(Environment.getExternalStorageDirectory(),fileName);
		if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
			try {
				inputStream=new FileInputStream(file);
				int len=0;
				byte[] data=new byte[1024];
				while ((len=inputStream.read(data))!=-1) {
					outputStream.write(data,0,len);
				}
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}finally{
				if(inputStream!=null){
					try {
						inputStream.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}
		
		return new String(outputStream.toByteArray());
	}
	/**
	 * 
	 * @param fileName 文件名稱
	 * @param content  文件內容
	 * @return
	 */
	public boolean saveContentToSdcard(String fileName,String content){
		boolean flag=false;
		FileOutputStream fileOutputStream=null;
//		獲得sdcard卡所在的路徑
		File file=new File(Environment.getExternalStorageDirectory(),fileName);
//		判斷sdCard是否可用
		if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
			try {
				fileOutputStream=new FileOutputStream(file);
				fileOutputStream.write(content.getBytes());
				flag=true;
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}finally{
				if(fileOutputStream!=null){
					try {
						fileOutputStream.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}
		return flag;
	}
}
MyTest.java文件:

public class MyTest extends AndroidTestCase {

	private final String TAG="MyTest";
	public MyTest() {
		// TODO Auto-generated constructor stub
	}
	
//在sdCard中寫入文件
	public void saveFile(){
		Context context=getContext();
		FileService fileService=new FileService(context);
		boolean flag=fileService.saveContentToSdcard("hello.txt", "你好");
		Log.i(TAG, "-->>"+flag);
		
	}
	
//	讀取sdCard中文件的內容
	public void readFile(){
		Context context=getContext();
		FileService fileService=new FileService(context);
		String msgString=fileService.getFileFromSdcard("hello.txt");
		Log.i(TAG, "-->>"+msgString);
	}
}
AndroidManifest.xml文件:

<span style="color:#cc66cc;">  </span><!-- 添加讀寫sdcard的授權 -->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <!-- 單元測試 -->
    <instrumentation
        android:name="android.test.InstrumentationTestRunner"
        android:targetPackage="com.example.android_sdcard" >
    </instrumentation>
<application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <!-- 這裏加一句話 -->
        <uses-library android:name="android.test.runner"/>
        <activity
            android:name="com.example.android_sdcard.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章