de.handtwerk.android.IoHelper.java Source code

Java tutorial

Introduction

Here is the source code for de.handtwerk.android.IoHelper.java

Source

/*
 *  Copyright 2012 Arne Handt, http://handtwerk.de
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package de.handtwerk.android;

import android.content.Context;
import android.content.res.AssetManager;
import android.os.AsyncTask;
import android.os.Environment;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.ref.SoftReference;
import java.util.HashMap;

/**
 * I/O related convenience methods.
 *
 * @author Arne Handt, it@handtwerk.de
 */
public class IoHelper {

    // Constants ---------------------------------------------------------

    private static final HashMap<String, SoftReference<JSONArray>> JSON_ARRAY_CACHE = new HashMap<String, SoftReference<JSONArray>>();

    private static final HashMap<String, SoftReference<JSONObject>> JSON_OBJECT_CACHE = new HashMap<String, SoftReference<JSONObject>>();

    // Static Methods ----------------------------------------------------

    public static void copyInBackground(InputStream pIn, OutputStream pOut, TaskCallback<Void, Void> pCallback) {

        new CopyTask(pIn, pOut, pCallback).execute();
    }

    public static void copy(InputStream pIn, OutputStream pOut) throws IOException {

        byte[] buffer = new byte[1024];
        int read;
        while ((read = pIn.read(buffer)) != -1) {
            pOut.write(buffer, 0, read);
        }

        pIn.close();
        pOut.flush();
        pOut.close();
    }

    public static String readRawResourceAsString(int pId, Context pContext) throws IOException {

        InputStream is = pContext.getResources().openRawResource(pId);
        return StringHelper.readStream(is);
    }

    public static String readAssetAsString(String pPath, Context pContext) throws IOException {

        AssetManager assMan = pContext.getAssets();
        InputStream is = assMan.open(pPath);
        return StringHelper.readStream(is);
    }

    public static JSONObject readAssetAsJsonObject(String pPath, Context pContext)
            throws IOException, JSONException {

        synchronized (JSON_OBJECT_CACHE) {

            SoftReference<JSONObject> ref = JSON_OBJECT_CACHE.get(pPath);
            if (ref != null && ref.get() != null) {

                return ref.get();
            }

            String jsonStr = readAssetAsString(pPath, pContext);
            JSONObject json = new JSONObject(jsonStr);

            JSON_OBJECT_CACHE.put(pPath, new SoftReference<JSONObject>(json));
            return json;
        }
    }

    public static JSONArray readAssetAsJsonArray(String pPath, Context pContext) throws IOException, JSONException {

        synchronized (JSON_ARRAY_CACHE) {

            SoftReference<JSONArray> ref = JSON_ARRAY_CACHE.get(pPath);
            if (ref != null && ref.get() != null) {

                return ref.get();
            }

            String jsonStr = readAssetAsString(pPath, pContext);
            JSONArray json = new JSONArray(jsonStr);

            JSON_ARRAY_CACHE.put(pPath, new SoftReference<JSONArray>(json));
            return json;
        }
    }

    public static File getExternalAppStoragePath(String pPath, Context pContext) {

        String path = "/Android/data/" + pContext.getApplicationInfo().packageName + "/files/" + pPath;
        return new File(Environment.getExternalStorageDirectory(), path);
    }

    // Inner Classes -----------------------------------------------------

    static class CopyTask extends AsyncTask<Void, Void, Void> {

        // Instance Fields ---------------------------------------------------

        private InputStream mIn;

        private OutputStream mOut;

        private Throwable mError;

        private TaskCallback<Void, Void> mCallback;

        // Constructors ------------------------------------------------------

        CopyTask(InputStream pIn, OutputStream pOut, TaskCallback<Void, Void> pCallback) {

            mIn = pIn;
            mOut = pOut;
            mCallback = pCallback;
        }

        @Override
        protected Void doInBackground(Void... pArg0) {

            try {

                mError = null;
                copy(mIn, mOut);

            } catch (Throwable e) {

                mError = e;
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void pResult) {

            if (mError == null) {

                mCallback.onSuccess(null, null);

            } else {

                mCallback.onFailure(null, mError);
            }
        }

    }

}