安卓(Android) 怎么通过inputstreamreader和utf-8编码读取Asset文本

2019年10月17日22:26:28安卓(Android) 怎么通过inputstreamreader和utf-8编码读取Asset文本已关闭评论 353 1009字阅读3分21秒

1.简介

安卓(Android) 怎么通过inputstreamreader和utf-8编码读取Asset文本?——请看下文。

2.示例代码

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


import android.content.Context;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;

public class Main {
    static List<String> readAssetsText(Context context, String assetName)
            throws IOException {
        InputStream is = null;
        InputStreamReader isr = null;
        BufferedReader br = null;
        List<String> lines = new ArrayList<String>();
        try {
            is = context.getAssets().open(assetName);
            isr = new InputStreamReader(is, "UTF-8");
            br = new BufferedReader(isr);
            String line = null;
            while ((line = br.readLine()) != null) {
                lines.add(line);
            }
        } finally {
            closeQuietly(br);
            closeQuietly(isr);
            closeQuietly(is);
        }
        return lines;
    }

    private static void closeQuietly(InputStream is) {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static void closeQuietly(Reader reader) {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

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