android 读取asset文件方法封装

来源:互联网 发布:three.js 热点 编辑:程序博客网 时间:2024/06/04 01:28

话不多说先上代码:

MetaInfoManager 是封装读取asset的工具类

public class MetaInfoManager {

privatestatic final StringTAG = "MetaInfoManager";

private static final MetaInfoManager instance = new MetaInfoManager();

public static final MetaInfoManager getInstance() {

returninstance;

}

private JSONObjectdata;

private MetaInfoManager() {

try {

AssetManager assetMgr = WuyouSDK.getContext().getAssets();//sdk 获取context上下文

InputStream inputStream = assetMgr.open("wuyou_data.json");

String jsonString = IOUtils.readContent(inputStream,"UTF-8", inputStream.available());

inputStream.close();

data = new JSONObject(jsonString);

} catch (Exception e) {

Log.e(TAG,"Wuyou Data file is not exist. Please check assets/wuyou_data.json.", e);

}

}

public boolean getBoolean(String name, boolean fallback) {

try {

return data.getBoolean(name);

} catch (NullPointerException e) {

Log.e(TAG,"Meta-data is null. Please check your assets/wuyou_data.json: " + name);

} catch (JSONException e) {

Log.e(TAG,"Meta-data not found: " + name);

}

return fallback;

}

public String getString(String name, String fallback)throws NullPointerException {

try {

return data.getString(name);

} catch (JSONException e) {

Log.e(TAG,"Meta-data not found: " + name);

}

return fallback;

}

public long getLong(String name, long fallback) {

try {

return data.getLong(name);

} catch (NullPointerException e) {

Log.e(TAG,"Meta-data is null. Please check your assets/wuyou_data.json: " + name);

} catch (JSONException e) {

Log.e(TAG,"Meta-data not found: " + name);

}

return fallback;

}

public int getInt(String name, int fallback) {

try {

return data.getInt(name);

} catch (NullPointerException e) {

Log.e(TAG,"Meta-data is null. Please check your assets/wuyou_data.json: " + name);

} catch (JSONException e) {

Log.e(TAG,"Meta-data not found: " + name);

}

return fallback;

}

}

第二个类 IOUtils 读取asset里面的内容,健值对对应:


public class IOUtils {

privatestatic final StringTAG = "IOUtils";

/**

* @param inputStream

* @param encoding

* @param contentLength

* @return

*/

public static String readContent(final InputStream inputStream, String encoding,int contentLength) {

String contentString = null;

// Allocate StringBuilder

StringBuilder stringBuilder = null;

if (contentLength > 0) {

stringBuilder = new StringBuilder(contentLength);

}

else {

stringBuilder = new StringBuilder();

}

// Read content

try {

final ReadableByteChannel inputChannel = Channels.newChannel(inputStream);

final ByteBuffer buffer = ByteBuffer.allocate(16*1024);

while (inputChannel.read(buffer) > 0) {

// prepare the buffer to be drained

buffer.flip();

stringBuilder.append(Charset.forName(encoding).newDecoder().decode(buffer).toString());

}

contentString = stringBuilder.toString();

inputChannel.close();

} catch (Exception e) {

Log.e(TAG,null, e);

}

return contentString;

}

/**

* @param fileChannel

* @param encoding

* @return

*/

public static String readContent(FileChannel fileChannel, String encoding) {

String contentString = null;

int size = 0;

try {

size = safeLongToInt(fileChannel.size());

} catch (IllegalArgumentException e1) {

Log.d(TAG,null, e1);

} catch (IOException e1) {

Log.d(TAG,null, e1);

}

// Allocate StringBuilder

StringBuilder stringBuilder = null;

if (size > 0) {

stringBuilder = new StringBuilder(size);

}

else {

stringBuilder = new StringBuilder();

}

// Read content

try {

final ByteBuffer buffer = ByteBuffer.allocate(16*1024);

while (fileChannel.read(buffer) > 0) {

// prepare the buffer to be drained

buffer.flip();

stringBuilder.append(Charset.forName(encoding).newDecoder().decode(buffer).toString());

}

contentString = stringBuilder.toString();

} catch (Exception e) {

Log.e(TAG,null, e);

}

return contentString;

}

/**

* @param l

* @return

* @throws IllegalArgumentException

*/

public static int safeLongToInt(long l)throws IllegalArgumentException {

    if (l < Integer.MIN_VALUE || l > Integer.MAX_VALUE) {

        thrownew IllegalArgumentException

            (l +" cannot be cast to int without changing its value.");

    }

    return (int) l;

}

/**

* @param inputChannel

* @param outputChannel

* @throws IOException

*/

public static void fastChannelCopy(final ReadableByteChannel inputChannel,final WritableByteChannel outputChannel) throws IOException {

final ByteBuffer buffer = ByteBuffer.allocateDirect(16 * 1024);

while (inputChannel.read(buffer) > 0) {

// prepare the buffer to be drained

buffer.flip();

// write to the channel, may block

outputChannel.write(buffer);

// If partial transfer, shift remainder down

// If buffer is empty, same as doing clear()

buffer.compact();

}

// EOF will leave buffer in fill state

buffer.flip();

// make sure the buffer is fully drained.

while (buffer.hasRemaining()) {

outputChannel.write(buffer);

}

}

/**

* @param inputStream

* @param size

* @return

*/

public static byte[] read(final InputStream inputStream,int size) {

final ReadableByteChannel inputChannel = Channels.newChannel(inputStream);

ByteArrayOutputStream outputStream;

if (size > 0) {

outputStream = new ByteArrayOutputStream(size);

}

else {

outputStream = new ByteArrayOutputStream();

}

final WritableByteChannel outputChannel = Channels.newChannel(outputStream);

try {

fastChannelCopy(inputChannel, outputChannel);

} catch (IOException e) {

Log.d(TAG,null, e);

}

return outputStream.toByteArray();

}

/**

* @param fileChannel

* @return

*/

public static byte[] read(final FileChannel fileChannel) {

int size = 0;

try {

size = safeLongToInt(fileChannel.size());

} catch (IllegalArgumentException e1) {

Log.d(TAG,null, e1);

} catch (IOException e1) {

Log.d(TAG,null, e1);

}

ByteArrayOutputStream outputStream;

if (size > 0) {

outputStream = new ByteArrayOutputStream(size);

}

else {

outputStream = new ByteArrayOutputStream();

}

final WritableByteChannel outputChannel = Channels.newChannel(outputStream);

try {

fastChannelCopy(fileChannel, outputChannel);

} catch (IOException e) {

Log.d(TAG,null, e);

}

return outputStream.toByteArray();

}


/**

* @param uriParams

* @return

*/

public static HashMap<String, String> getMapFromUriParams(String uriParams) {

HashMap<String, String> keyValueMap = new HashMap<String, String>();

StringTokenizer entryTokenizer = new StringTokenizer(uriParams, "&");

while(entryTokenizer.hasMoreTokens()) {

String entry = entryTokenizer.nextToken();

StringTokenizer kayValueTokenizer = new StringTokenizer(entry, "=");

String key = kayValueTokenizer.nextToken();

String value = kayValueTokenizer.nextToken();

keyValueMap.put(key, value);

}

return keyValueMap;

}

/**

* @param postDataBundle

* @returnhttp post form data

*/

public static String getHttpPostFormData(Bundle postDataBundle) {

        Set<String> postDataKeySet = postDataBundle.keySet();

        

        StringBuilder postDataBuilder = new StringBuilder();

        for (String key : postDataKeySet) {

        if (postDataBuilder.length() > 0) {

        postDataBuilder.append("&");

        }

        String value = postDataBundle.getString(key);

        postDataBuilder.append(key+"="+value);

        }

        

        String postData = postDataBuilder.toString();

        

        return postData;

}


3。使用方法

 MetaInfoManager.getInstance().getString("value","默认的值");


0 0
原创粉丝点击