安卓(Android) 怎么从Asset中读取文本文件

2019年10月17日22:30:56安卓(Android) 怎么从Asset中读取文本文件已关闭评论 340 1056字阅读3分31秒

1.简介

安卓(Android) 怎么从Asset中读取文本文件?——请看下文。

2.示例代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

import android.content.Context;

import android.content.res.AssetManager;

public class Main {
    
    public static String read(Context context, String fileName) {
        try {
            AssetManager am = context.getAssets();
            InputStream in = am.open(fileName);
            
            
            
            
            String txt = read(new InputStreamReader(in));
            return txt;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    
    public static String read(Reader r) {
        try {
            BufferedReader reader = r instanceof BufferedReader ? (BufferedReader) r
                    : new BufferedReader(r);
            final int bufSize = 8192; 
            
            StringBuilder sb = new StringBuilder(bufSize);
            char[] cbuf = new char[bufSize];
            while (true) {
                int chars = reader.read(cbuf);
                if (chars == -1)
                    break;
                sb.append(cbuf, 0, chars);
            }
            return sb.toString();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                r.close();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }

    public static String read(InputStream inputStream) {
        return read(new InputStreamReader(inputStream));
    }
}

 
继续阅读
编程十万个怎么办