安卓(Android) 怎么从Asset加载utf-8文本

2019年10月17日22:26:14安卓(Android) 怎么从Asset加载utf-8文本已关闭评论 334 928字阅读3分5秒

1.简介

安卓(Android) 怎么从Asset加载utf-8文本?——请看下文。

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.io.StringWriter;
import java.io.Writer;

public class Main {
    private static final String ENCODING = "utf-8";

    public static String loadText(Context context,
            @SuppressWarnings("SameParameterValue") String assetFielPath) {
        InputStream is;
        try {
            is = context.getResources().getAssets().open(assetFielPath);
            return convertStreamToString(is);
        } catch (IOException e) {
            
            e.printStackTrace();
        }

        return null;
    }

    private static String convertStreamToString(InputStream is)
            throws IOException {
        Writer writer = new StringWriter();

        char[] buffer = new char[2048];
        try {
            Reader reader = new BufferedReader(new InputStreamReader(is,
                    ENCODING));
            int n;
            while ((n = reader.read(buffer)) != -1) {
                writer.write(buffer, 0, n);
            }
        } finally {
            is.close();
        }
        return writer.toString();
    }
}

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