
第十四課:讀寫文件File Access
本文介紹如何建立及存取文件。在android中,存儲裝置分為內部存儲(Internal Storage)和外部存儲(External Storage)。內部存儲是個私人的空間,默認只有你的app可以存取。當你uninstall app的時候,那些文件也會被移除。外部存儲則指SD card,所有apps都可以存取外部存儲上的文件。這demo展示如何可以把資料存放在內部存儲上。
我們要學會使用兩個function:openFileOutput()和openFileInput()。
openFileOutput()用來打開內部存儲裝置。把文件名提供到openFileOutput(),便會回傳一個fileOutputStream。 我們把資料經byte array寫入到這文件。
String FILENAME = "filedemo.txt"; String content = txtMessage.getText().toString(); FileOutputStream fos = openFileOutput(FILENAME, MODE_PRIVATE); fos.write(content.getBytes()); fos.close();
openFileInput()跟openFileOutput()一樣容易。同樣地,只要提供文件名,便會回傳一個FileInputStream。
FileInputStream fis = openFileInput(FILENAME); InputStreamReader isr = new InputStreamReader(fis); BufferedReader br = new BufferedReader(isr); String sLine = null; String sOutput = ""; while ((sLine = br.readLine())!=null) sOutput += sLine; Toast.makeText(this, sOutput, Toast.LENGTH_SHORT).show();
這樣就完成了!你也不用在androidmanifest.xml中設定權限。
Download: FileDemo