1. 前言

在Android开发过程中,会把一些资源文件,放在assets下。然后通过getAssets()去读取数据流

2. 如何打开assets中的文件流?

可以使用getAssets().open()来实现

context.getAssets().open(fileName)

3. 实现代码封装

import android.content.Context;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class AssetsReader {

    /**
     * 读取assets目录下的文本文件内容
     * @param context 上下文对象
     * @param fileName 文件名(如:"book_text.txt")
     * @return 文件内容字符串,如果读取失败则返回null
     */
    public static String readTextFromAssets(Context context, String fileName) {
        StringBuilder stringBuilder = new StringBuilder();
        BufferedReader reader = null;
        
        try {
            // 打开assets中的文件流
            InputStream is = context.getAssets().open(fileName);
            reader = new BufferedReader(new InputStreamReader(is));
            
            String line;
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line);
                stringBuilder.append("\n"); // 保留换行符
            }
            
            // 移除最后一个多余的换行符
            if (stringBuilder.length() > 0) {
                stringBuilder.deleteCharAt(stringBuilder.length() - 1);
            }
            
            return stringBuilder.toString();
            
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

4. 使用方法

// 在你的Activity或Fragment中调用
String bookContent = AssetsReader.readTextFromAssets(context, "book_text.txt");
if (bookContent != null) {
    // 使用读取到的内容
    textView.setText(bookContent);
} else {
    // 处理读取失败的情况
    Toast.makeText(context, "读取文件失败", Toast.LENGTH_SHORT).show();
}

4. 注意事项

  1. 确保文件已放在src/main/assets/目录下(如果没有assets目录,需要手动创建)
  2. 如果是大文件,建议在子线程中调用此方法
  3. 文件名需要包含扩展名(如".txt")

5. 关于作者其它项目视频教程介绍

  1. Android新闻资讯app实战:https://www.bilibili.com/video/BV1CA1vYoEad/?vd_source=984bb03f768809c7d33f20179343d8c8
  2. Androidstudio开发购物商城实战:https://www.bilibili.com/video/BV1PjHfeXE8U/?vd_source=984bb03f768809c7d33f20179343d8c8
  3. Android开发备忘录记事本实战:https://www.bilibili.com/video/BV1FJ4m1u76G?vd_source=984bb03f768809c7d33f20179343d8c8&spm_id_from=333.788.videopod.sections
  4. Androidstudio底部导航栏实现:https://www.bilibili.com/video/BV1XB4y1d7et/?spm_id_from=333.337.search-card.all.click&vd_source=984bb03f768809c7d33f20179343d8c8
  5. Android使用TabLayout+ViewPager2实现左右滑动切换:https://www.bilibili.com/video/BV1Mz4y1c7eX/?spm_id_from=333.337.search-card.all.click&vd_source=984bb03f768809c7d33f20179343d8c8
Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐