Android 程式開發:(十八)檔案 —— 18.2儲存到外部存放裝置(SD卡)

來源:互聯網
上載者:User

上一節介紹了如何把檔案儲存體到內部裝置。有的時候,需要把檔案儲存體到外部存放裝置,比如SD卡。因為SD卡具有更大的儲存空間,同時也可以很容易的和其他使用者分享這些檔案。

使用上一節的例子,把使用者輸入的文字儲存在SD卡,修改onClick()事件。如下:

public class FilesActivity extends Activity {EditText textBox;static final int READ_BLOCK_SIZE = 100;/** Called when the activity is first created. */@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);textBox = (EditText) findViewById(R.id.txtText1);        InputStream is = this.getResources().openRawResource(R.raw.textfile);        BufferedReader br = new BufferedReader(new InputStreamReader(is));        String str = null;        try {            while ((str = br.readLine()) != null) {                Toast.makeText(getBaseContext(),                     str, Toast.LENGTH_SHORT).show();            }            is.close();            br.close();        } catch (IOException e) {            e.printStackTrace();        }}public void onClickSave(View view) {String str = textBox.getText().toString();try{            //---SD Card Storage---            File sdCard = Environment.getExternalStorageDirectory();            File directory = new File (sdCard.getAbsolutePath() +                "/MyFiles");            directory.mkdirs();            File file = new File(directory, "textfile.txt");            FileOutputStream fOut = new FileOutputStream(file);            /*FileOutputStream fOut =openFileOutput("textfile.txt",MODE_WORLD_READABLE);*/                        OutputStreamWriter osw = newOutputStreamWriter(fOut);//---write the string to the file---osw.write(str);osw.flush(); osw.close();//---display file saved message---Toast.makeText(getBaseContext(),"File saved successfully!",Toast.LENGTH_SHORT).show();//---clears the EditText---textBox.setText("");}catch (IOException ioe){ioe.printStackTrace();}}}

上面的代碼中,使用getExternalStorageDirectory()方法去擷取SD卡的路徑。通常,在真機上面返回“/sdcard”,在模擬器上面返回"/mnt/sdcard"。但是,不要嘗試去寫死SD卡的路徑,因為手機廠商有可能去給SD卡指定一個路徑。因此,確保使用getExternalStorageDirectory()方法去擷取SD卡的路徑。

然後,建立一個MyFiles的檔案夾。最終,把檔案儲存在這個檔案夾中。

從外部裝置中負載檔案,修改onClickLoad()方法:

public void onClickLoad(View view) {try{//---SD Storage---            File sdCard = Environment.getExternalStorageDirectory();            File directory = new File (sdCard.getAbsolutePath() +                 "/MyFiles");            File file = new File(directory, "textfile.txt");            FileInputStream fIn = new FileInputStream(file);            InputStreamReader isr = new InputStreamReader(fIn);            /*FileInputStream fIn = openFileInput("textfile.txt");InputStreamReader isr = new InputStreamReader(fIn);            */            char[] inputBuffer = new char[READ_BLOCK_SIZE];String s = "";int charRead;while ((charRead = isr.read(inputBuffer))>0){//---convert the chars to a String---String readString =String.copyValueOf(inputBuffer, 0,charRead);s += readString;inputBuffer = new char[READ_BLOCK_SIZE];}//---set the EditText to the text that has been // read---textBox.setText(s);Toast.makeText(getBaseContext(),"File loaded successfully!",Toast.LENGTH_SHORT).show();}catch (IOException ioe) {ioe.printStackTrace();}}

請注意,如果想要往SD卡中寫入檔案,需要在AndroidManifest.xml中加入相關的許可權:

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="net.manoel.Files"    android:versionCode="1"    android:versionName="1.0" >    <uses-sdk android:minSdkVersion="10" />    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />            <application        android:icon="@drawable/ic_launcher"        android:label="@string/app_name" >        <activity            android:label="@string/app_name"            android:name=".FilesActivity" >            <intent-filter >                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>    </application></manifest>

執行上述代碼,查看SD卡:

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.