读取Assets目录下的文件 - Android

本篇文章记录的是在Android应用中读取Assets目录下的文件.

下面是一段代码示例:

package com.example.myapplication.assets;

import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.example.myapplication.R;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

public class AssetsActivity extends AppCompatActivity implements View.OnClickListener {


    private EditText editText;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.assets_activity);
        editText = findViewById(R.id.edit_text);
        // 此处用于开始读取文件
        try (InputStream is = getResources().getAssets().open("yuansudong.txt")) {
            int length = is.available();
            byte[] buffer = new byte[length];
            int readLen = is.read(buffer);
            if (readLen != length) {
                throw new IOException("长度不一致");
            }
            editText.setText(new String(buffer, StandardCharsets.UTF_8));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    @Override
    public void onClick(View v) {
    }
}

上面的代码执行完毕之后,会得到诸如下面的结果: