安卓(Android) 怎么通过路径获取Asset字符串数据

2019年10月18日21:49:17安卓(Android) 怎么通过路径获取Asset字符串数据已关闭评论 320 1513字阅读5分2秒

1.简介

安卓(Android) 怎么通过路径获取Asset字符串数据?——请看下文。

2.示例代码

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


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

public class Main {
    public static String getAssetData(Context context, String path) {
        InputStream is = null;
        String ret = null;

        try {
            is = context.getAssets().open(path);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

        try {
            ret = read(is);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            closeQuietly(is);
        }
        return ret;
    }

    public static String getAssetData(Context context, String path,
            String charset) {
        InputStream is = null;
        String ret = null;

        try {
            is = context.getAssets().open(path);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

        try {
            ret = read(is, charset);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            closeQuietly(is);
        }
        return ret;
    }

    
    public static String read(InputStream in) throws IOException {
        StringBuilder sb = new StringBuilder();
        BufferedReader r = new BufferedReader(new InputStreamReader(in),
                1000);
        for (String line = r.readLine(); line != null; line = r.readLine()) {
            sb.append(line);
        }
        return sb.toString();
    }

    public static String read(InputStream in, String charset)
            throws IOException {
        StringBuilder sb = new StringBuilder();
        BufferedReader r = new BufferedReader(new InputStreamReader(in,
                charset), 1000);
        for (String line = r.readLine(); line != null; line = r.readLine()) {
            sb.append(line);
        }
        return sb.toString();
    }

    public static java.io.IOException closeQuietly(java.io.Closeable stream) {
        if (stream == null) {
            return null;
        }

        try {
            stream.close();
        } catch (java.io.IOException e) {
            return e;
        }

        return null;
    }
}

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