[Android]存取External Storage

在權限的部分,需在Manifest檔內加入:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
前者為設定可讀寫的權限。是必備的。
後者是設定可掛載或是卸載可移除式儲存裝置。(如沒有加入這個權限,則在進行檔案操作時,會出現"Permission Denied"的錯誤訊息)。

A.之後在進行檔案寫入的動作時
    1.如果是要寫入二進位的資料,可用FileOutputStream.write()直接寫出檔案。
private void WriteData(String Data)  
{
//Check the state of storage
    if( !Environment.MEDIA_MOUNTED.equals((Environment.getExternalStorageState())) ) {  
        Log.d("WriteData", "--SDCard has been removed.--");  
        return;  
    }  

    try  
    {  
    //Get the path of root folder  
        File rootDir = Environment.getExternalStorageDirectory();  

    //Create a output stream object  
        FileOutputStream outStream = new FileOutputStream(new File(rootDir.getPath(), "IOTestFile.dat"));  

    //Write Data  
        byte[] buffer = new byte[BUFFER_SIZE];  
        buffer[0] = 0x30;  
        buffer[1] = 0x31;  
        buffer[2] = 0x32;  
        buffer[3] = 0x33;  
        buffer[4] = 0x34;  
        outStream.write(buffer, 0, 5);  

    //Flush it  
        outStream.flush();  

    //Close self  
        outStream.close();  

    }catch(Exception e){  
        Log.d("--WriteData--", e.getMessage());  
    }          
}  
要注意的是,使用FileOutputStream時,要把FileOutputStream放到try...catch()內。 Environment.getExternalStorageDirectory()可以取得到目前External storage所在的路徑。
    2.如果是要寫入純文字檔,可用FileOutputStream與OutputStreamWriter.append()來將資料寫入檔案內。
private void WriteDataWithOutputStreamWriter()  
{  
    try  
    {  
        String FuncName = "WriteDataWithOutputStreamWriter";  

    //Check the SDCard state  
        if(!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()))  
        {  
            Log.d("WriteDataWithOutputStreamWriter", "======== External SD Card not mounted ===========");  
            return;  
        }  

    //Get the path of the root folder  
        File rootDir = Environment.getExternalStorageDirectory();  

    //Create file object  
        File FileContent = new File(String.format("%s/%s/IOTestFile.dat", rootDir.getParent(), rootDir.getName()));  

        if(!FileContent.createNewFile())  
        {  
            Log.d(FuncName, "Cannot create file");  
        }  
        Log.d("WriteDataWithOutputStreamWriter", String.format("======= Target Path = %s ============", FileContent.getPath()));  

    //Create a output stream object  
        FileOutputStream outStream = new FileOutputStream(FileContent);  

    //Create a output stream writer  
        OutputStreamWriter streamWriter = new OutputStreamWriter(outStream);  

    //write data  
        streamWriter.append("lalalala");  

    //close writer  
        streamWriter.close();  

    //close output stream object  
        outStream.close();  
    }catch(Exception e){  
        Log.d("--WriteDataByOutputStreamWriter--", e.getMessage());  
    }
}  
B.如果是要讀取檔案,則可以用:
    1.讀取二進位檔的內容,則可用FileInputStream來取得資料即可。
private String ReadData()  
{  
    try  
    {  
    //Get the path of root folder  
        File rootDir = Environment.getExternalStorageDirectory();  

    //Create a input Stream Object  
        FileInputStream inStream = new FileInputStream(new File(rootDir.getPath(), "IOTestFile.dat"));  

    //Load the data from target  
        byte[] buffer = new byte[BUFFER_SIZE];  
        int DataLen = inStream.read(buffer);  
        if(DataLen == -1)  
        {  
            Log.d("ReadData", "========= Reading Data has problem. ==================");  
            throw new IOException("Reading Data has problem.");  
        }  

        inStream.close();  

    //Show data  
        TextView text = (TextView)findViewById(R.id.editText1);  
        String OutText = "";  
        for(int i = 0 ; i < 5 ; i++)  
        {  
            Log.d("ReadData", String.format("--------- Data(%x) has been loaded from %s -------------", buffer[i], rootDir.getPath()));  
            OutText += String.format("%x", buffer[i]);  
        }  

        text.setText((CharSequence)OutText);
    }catch(Exception e){  
        Log.d("--ReadData--", e.getMessage());  
    }  
    return "";  
}  

No comments:

Post a Comment

Build docker image from multiple build contexts

Build docker image from multiple build contexts ...