來自Resources和Assets 中的文件只可以讀取而不能進行寫的操作。
assets文件夾里面的文件都是保持原始的文件格式,需要用AssetManager以字節流的形式讀取文件。
1. 先在Activity里面調用getAssets() 來獲取AssetManager引用。
2. 再用AssetManager的open(String fileName, int accessMode) 方法則指定讀取的文件以及訪問模式就能得到輸入流InputStream。
3. 然后就是用已經open file 的inputStream讀取文件,讀取完成后記得inputStream.close() 。
4.調用AssetManager.close() 關閉AssetManager。
實現步驟:
1.分別創建assets文件夾和res/raw文件夾:(要注意的raw文件是在res下new,然后創建一個名字為raw的文件夾)


2.創建兩個txt文件,復制到asset和raw文件夾中:

3.實現的效果:

4.實現代碼:
(1)布局文件:
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="base.readassetsfile.MainActivity"> <Button android:textSize="20sp" android:text="@string/aasets_txt" android:id="@+id/readFile" android:layout_width="match_parent" android:layout_height="wrap_content" /> <Button android:textSize="20sp" android:text="@string/raw" android:id="@+id/readRawFile" android:layout_width="match_parent" android:layout_height="wrap_content" /></LinearLayout>
(2)具體實現:
package base.readassetsfile;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.util.Log;import android.view.View;import android.widget.EditText;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.io.UnsupportedEncodingException;public class MainActivity extends AppCompatActivity implements View.OnClickListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); findViewById(R.id.readFile).setOnClickListener(this); findViewById(R.id.readRawFile).setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.readFile: readAsset(); break; case R.id.readRawFile: readRaw(); break; } } public void readAsset(){ try { //獲取文件中的字節 InputStream inputStream=getResources().getAssets().open("Test.txt"); //將字節轉換為字符 InputStreamReader isReader=new InputStreamReader(inputStream,"UTF-8"); //使用bufferReader去讀取內容 BufferedReader reader=new BufferedReader(isReader); String out=""; while((out=reader.readLine())!=null){ Log.d("讀取到的文件信息:",out); } } catch (IOException e) { e.printStackTrace(); } } public void readRaw(){ try { //獲取文件中的內容 InputStream inputStream=getResources().openRawResource(R.raw.test); //將文件中的字節轉換為字符 InputStreamReader isReader=new InputStreamReader(inputStream,"UTF-8"); //使用bufferReader去讀取字符 BufferedReader reader=new BufferedReader(isReader); String out=""; try { while((out=reader.readLine())!=null){ Log.d("從raw文件夾中讀取到的數據:",out); } } catch (IOException e) { e.printStackTrace(); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } }}以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答