android之檔案操作——讀取assets和raw檔案下的內容
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(); } }}
感謝閱讀,希望能協助到大家,謝謝大家對本站的支援!