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"><Buttonandroid:textSize="20sp"android:text="@string/aasets_txt"android:id="@+id/readFile"android:layout_width="match_parent"android:layout_height="wrap_content" /><Buttonandroid: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 {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);findViewById(R.id.readFile).setOnClickListener(this);findViewById(R.id.readRawFile).setOnClickListener(this);}@Overridepublic 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();}}}
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!