Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 資源檔讀取教學:讀取 res/raw 中的檔案

編輯:關於 Android 開發

如何在 Android 中讀取資源檔

本文示範如何讀取放在 res/raw 資料夾中的資源檔,並把內容顯示出來。

布局檔:

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <Button android:id="@+id/read" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="讀取資源文件(Raw)" /> <TextView android:id="@+id/cont" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>

MainActivity.java:

package com.example.yanlei.wifi; import android.content.res.Resources; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; import java.io.IOException; import java.io.InputStream; import java.util.Scanner; public class MainActivity extends AppCompatActivity { private Button btnRead=null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnRead=(Button)super.findViewById(R.id.read); // 讀取資源文件 btnRead.setOnClickListener(new OnClickListener(){ public void onClick(View v) { // 獲取資源對象 Resources res=MainActivity.this.getResources(); // 通過 openRawResource() 讀取 R.raw.friend 資源,結果返回 InputStream InputStream input=res.openRawResource(R.raw.friend); // 讀取資源文件內容 Scanner scan=new Scanner(input); StringBuffer info=new StringBuffer(); while(scan.hasNext()) info.append(scan.next()).append("\n"); scan.close(); try { input.close(); } catch (IOException e) { e.printStackTrace(); } Toast.makeText(getApplicationContext(), info.toString(),Toast.LENGTH_LONG).show(); } }); } }

我們把 friend.txt 檔保存到 res/raw 資料夾中。

注意:raw 資料夾預設並不存在,需要你手動建立。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved