Android 程式開發:(十八)檔案 —— 18.4使用靜態資源

來源:互聯網
上載者:User

除了可以在運行時去建立並使用檔案,也可以在設計階段把檔案放在程式包中,這樣一來就可以在運行時去使用他們。舉個例子,你想把一些協助檔案打包進程式,當使用者需要的時候,就可以展示給他們看。在這種情況下,應該把檔案放在res/raw檔案夾下面。

想要在代碼中使用這個檔案,需要調用Activity的getResources()方法,返回一個Resources對象。然後,使用它的openRawResource()方法去開啟res/raw檔案夾中的檔案:

/** 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();        }}

注意,textfile.txt的id是R.raw.textfile

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.