標籤:android style blog http color io os 使用 ar
android中資源是唯讀,不可寫。
下面我們來讀取Assets目錄和res/raw目錄下的文字檔到TextView中,首先要做的就是將檔案放入到這兩個檔案夾裡
在activity_main.xml中放入兩個TextView來顯示常值內容
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/LinearLayout1" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="com.ssln.fileresources.MainActivity" > <TextView android:id="@+id/tvRaw" android:layout_width="match_parent" android:layout_height="wrap_content" /> <TextView android:id="@+id/tvAssets" android:layout_width="match_parent" android:layout_height="wrap_content" /></LinearLayout>
然後在mainactivity.java中封裝了2個方法,分別讀取兩個目錄下的內容,一種是擷取內容大小,然後直接讀取到緩衝區,另外一種是逐行讀取檔案內容
package com.ssln.fileresources;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import org.apache.http.util.EncodingUtils;import android.app.Activity;import android.os.Bundle;import android.widget.TextView;import android.widget.Toast;public class MainActivity extends Activity { private final String Encoding = "utf-8"; // 檔案編碼 private final String fileName = "text.txt"; // 檔案名稱 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView tvAssets = (TextView) findViewById(R.id.tvAssets); TextView tvRaw = (TextView) findViewById(R.id.tvRaw); tvAssets.setText(ReadFromAssets()); tvRaw.setText(ReadFromRaw()); } /** * 讀取Assets目錄下的檔案 * * @return */ private String ReadFromAssets() { String retStr = ""; try { // 開啟檔案到流 InputStream inStream = getResources().getAssets().open(fileName); // 擷取長度 int fileLen = inStream.available(); // 放入緩衝區 byte[] buffer = new byte[fileLen]; inStream.read(buffer); // 轉碼到文本 retStr = EncodingUtils.getString(buffer, Encoding); //關閉 inStream.close(); } catch (IOException e) { e.printStackTrace(); } return retStr; } /** * 讀取Raw目錄下檔案 * * @return */ private String ReadFromRaw() { String retStr=""; try { InputStream inStream=getResources().openRawResource(R.raw.text); //這裡我們使用另外一種讀取方法,逐行讀取內容 BufferedReader br=new BufferedReader(new InputStreamReader(inStream)); String tempStr=""; while((tempStr=br.readLine())!=null) { retStr+=tempStr+"\r\n"; Toast.makeText(this, tempStr, Toast.LENGTH_SHORT).show(); } } catch(IOException e) { e.printStackTrace(); } return retStr; }}
我們看下效果
??? 為毛是亂碼尼?因為我們在上面讀取的編碼方式是utf-8的
private final String Encoding = "utf-8"; // 檔案編碼retStr = EncodingUtils.getString(buffer, Encoding);
腫麼辦?我們從新用記事本來儲存下檔案為utf-8就好了
在來看看效果
android讀取Resources中內容