Example usage for android.content.res AssetManager open

List of usage examples for android.content.res AssetManager open

Introduction

In this page you can find the example usage for android.content.res AssetManager open.

Prototype

public @NonNull InputStream open(@NonNull String fileName) throws IOException 

Source Link

Document

Open an asset using ACCESS_STREAMING mode.

Usage

From source file:edu.ncsu.asbransc.mouflon.recorder.UploadFile.java

private void encryptAndWriteAESKey(SecretKey aeskey, File dest)
        throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException,
        InvalidKeyException, IllegalBlockSizeException, BadPaddingException, NoSuchProviderException {
    Cipher keyc;/*from w ww.  jav  a  2 s.c  o m*/
    AssetManager am = getAssets();
    InputStream in = am.open("mouflon_key.pub");
    byte[] readFromFile = new byte[in.available()];
    //TODO check that this is 294 bytes and replace with a constant. in.available is not guaranteed to return a useful value
    in.read(readFromFile);
    keyc = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC");
    //ECB and CBC etc don't make sense for RSA, but the way this API is designed you have to specify something.
    KeyFactory kf = KeyFactory.getInstance("RSA");
    KeySpec ks = new X509EncodedKeySpec(readFromFile);
    RSAPublicKey key = (RSAPublicKey) kf.generatePublic(ks);
    keyc.init(Cipher.ENCRYPT_MODE, key);
    //byte[] encrpytedKey = keyc.doFinal(aeskey.getEncoded());
    FileOutputStream out = new FileOutputStream(dest);
    CipherOutputStream outcipher = new CipherOutputStream(out, keyc);
    outcipher.write(aeskey.getEncoded());
    outcipher.close();
    out.close();
}

From source file:com.qihoo.permmgr.PermManager.java

/**
 * asset/permmgr???/*w w w  .  j av  a  2  s.  c  o m*/
 */
private boolean checkFileSize(String paramString, File paramFile) {
    AssetManager assetManager = mContext.getAssets();
    try {
        InputStream is = assetManager.open("permmgr/" + paramString);
        if (is.available() == paramFile.length()) {
            return true;
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return false;
}

From source file:jahirfiquitiva.iconshowcase.tasks.CopyFilesToStorage.java

@Override
protected Boolean doInBackground(Void... params) {
    Boolean worked;/*from  w  ww. j a v a 2  s .  c  o m*/
    try {
        AssetManager assetManager = context.get().getAssets();
        String[] files = assetManager.list(folder);

        if (files != null) {
            for (String filename : files) {
                InputStream in;
                OutputStream out;
                if (filename.contains(".")) {
                    try {
                        in = assetManager.open(folder + "/" + filename);
                        out = new FileOutputStream(Environment.getExternalStorageDirectory().toString()
                                + "/ZooperWidget/" + getFolderName(folder) + "/" + filename);
                        copyFiles(in, out);
                        in.close();
                        out.close();
                    } catch (Exception e) {
                        //Do nothing
                    }
                }
            }
        }
        worked = true;
    } catch (Exception e2) {
        worked = false;
    }
    return worked;
}

From source file:org.deviceconnect.android.profile.restful.test.NormalFileProfileTestCase.java

/**
 * ???./*from ww w .j  a  va2 s.  c o  m*/
 * <pre>
 * Method: POST
 * Path: /file/send?deviceid=xxxx&filename=xxxx
 * </pre>
 * <pre>
 * ??
 * result?0???????
 * </pre>
 */
public void testSend() {
    final String name = "test.png";
    URIBuilder builder = TestURIBuilder.createURIBuilder();
    builder.setProfile(FileProfileConstants.PROFILE_NAME);
    builder.setAttribute(FileProfileConstants.ATTRIBUTE_SEND);
    builder.addParameter(DConnectProfileConstants.PARAM_DEVICE_ID, getDeviceId());
    builder.addParameter(DConnectMessage.EXTRA_ACCESS_TOKEN, getAccessToken());
    builder.addParameter(FileProfileConstants.PARAM_PATH, "/test/test.png");
    builder.addParameter(FileProfileConstants.PARAM_FILE_TYPE,
            String.valueOf(FileProfileConstants.FileType.FILE.getValue()));

    AssetManager manager = getApplicationContext().getAssets();
    InputStream in = null;
    try {
        MultipartEntity entity = new MultipartEntity();
        in = manager.open(name);
        // ??
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int len;
        byte[] buf = new byte[BUF_SIZE];
        while ((len = in.read(buf)) > 0) {
            baos.write(buf, 0, len);
        }
        // ?
        entity.addPart(FileProfileConstants.PARAM_DATA, new BinaryBody(baos.toByteArray(), name));

        HttpPost request = new HttpPost(builder.toString());
        request.setEntity(entity);

        JSONObject root = sendRequest(request);
        assertResultOK(root);
    } catch (JSONException e) {
        fail("Exception in JSONObject." + e.getMessage());
    } catch (IOException e) {
        fail("IOException in JSONObject." + e.getMessage());
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:anomalyDetector.activities.MainFeaturesActivity.java

@Override
protected void onStart() {
    super.onStart();

    selectedFeatures = new ArrayList<String>();
    /*//from   w ww.  j  av  a2  s. c  o m
     * Check if the service is running
     */
    ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
    List<ActivityManager.RunningServiceInfo> rs = am.getRunningServices(100);
    for (ActivityManager.RunningServiceInfo rsi : rs) {
        String serviceClassName = rsi.service.getClassName();
        if (serviceClassName.equals("anomalyDetector.services.ColectFeaturesService")) {
            isServiceRunning = true;
            drawerItemClickListener.setServiceRunning(true);
            break;
        }
    }

    // Enable or disable the buttons based on service status(running or not running)
    if (isServiceRunning) {
        startServiceButton.setEnabled(false);
        stopServiceButton.setEnabled(true);
    } else {
        startServiceButton.setEnabled(true);
        stopServiceButton.setEnabled(false);
    }

    /*
     * List of features that can be collected
     */
    AssetManager assetManager = getAssets();
    BufferedReader reader;

    /*
     * Read the features from assets and add them to the arraylist
     */
    try {
        reader = new BufferedReader(new InputStreamReader(assetManager.open("features.txt")));
        String line;
        while ((line = reader.readLine()) != null) {
            // Skip comments
            if (line.startsWith("#")) {
                continue;
            }
            selectedFeatures.add(line);
        }

        reader.close();

    } catch (IOException e) {
        Log.d("MainFeaturesActivity", "Error reading assets file");
    }

    // Create an adapter that holds the selected features
    // and pass it to the list view
    listViewAdapter = new ArrayAdapter<String>(this, R.layout.row, selectedFeatures);
    listView.setAdapter(listViewAdapter);
}

From source file:Main.java

private static boolean copyAsset(AssetManager am, File rep, boolean force) {
    boolean existingInstall = false;
    try {//  www.j  a v  a  2  s  .c o m
        String assets[] = am.list("");
        for (int i = 0; i < assets.length; i++) {
            boolean hp48 = assets[i].equals("hp48");
            boolean hp48s = assets[i].equals("hp48s");
            boolean ram = assets[i].equals("ram");
            boolean rom = assets[i].equals("rom");
            boolean rams = assets[i].equals("rams");
            boolean roms = assets[i].equals("roms");
            int required = 0;
            if (ram)
                required = 131072;
            else if (rams)
                required = 32768;
            else if (rom)
                required = 524288;
            else if (roms)
                required = 262144;
            //boolean SKUNK = assets[i].equals("SKUNK");
            if (hp48 || rom || ram || hp48s || roms || rams) {
                File fout = new File(rep, assets[i]);
                existingInstall |= fout.exists();
                if (!fout.exists() || fout.length() == 0 || (required > 0 && fout.length() != required)
                        || force) {
                    Log.i("x48", "Overwriting " + assets[i]);
                    FileOutputStream out = new FileOutputStream(fout);
                    InputStream in = am.open(assets[i]);
                    byte buffer[] = new byte[8192];
                    int n = -1;
                    while ((n = in.read(buffer)) > -1) {
                        out.write(buffer, 0, n);
                    }
                    out.close();
                    in.close();
                }
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return existingInstall;
}

From source file:com.semaphore.sm.MainActivity.java

private void copyAsset(String srcPath, String dstPath) throws IOException {
    AssetManager assetManager = getApplicationContext().getAssets();
    InputStream is = assetManager.open(srcPath);
    FileOutputStream fos = new FileOutputStream(dstPath, false);

    byte[] buffer = new byte[256];
    int n = -1;//from  w ww . j a  v a 2  s .  co m
    do {
        n = is.read(buffer);
        if (n != -1) {
            fos.write(buffer, 0, n);
        }
    } while (n != -1);
    fos.flush();
    fos.close();
    is.close();
}

From source file:com.jainbooks.activitys.DashboardActivity.java

private void copyAssets() {
    AssetManager assetManager = getAssets();
    InputStream in = null;/* w w  w  .jav  a2s.c  o  m*/
    OutputStream out = null;
    try {
        in = assetManager.open("book.pdf");
        File outFile = getExternalCacheDir();
        File file = new File(outFile, "book.pdf");
        out = new FileOutputStream(file);
        copyFile(in, out);
        in.close();
        in = null;
        out.flush();
        out.close();
        out = null;
        Log.e("tag", "copyed");
    } catch (IOException e) {
        Log.e("tag", "Failed to copy asset file: book.pdf ", e);
    }

}

From source file:cz.urbangaming.galgs.GAlg.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

    ActionBar actionBar = getActionBar();
    actionBar.setDisplayHomeAsUpEnabled(false);
    actionBar.setDisplayShowTitleEnabled(false);
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);

    ArrayList<String> itemList = new ArrayList<String>();
    //TODO:Make static, use String constants strings.xml
    itemList.add(getResources().getString(R.string.workmode_add));
    itemList.add(getResources().getString(R.string.workmode_edit));
    itemList.add(getResources().getString(R.string.workmode_delete));
    this.aAdpt = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1,
            itemList);/*from  ww w.ja  v  a 2 s .c  o  m*/
    actionBar.setListNavigationCallbacks(aAdpt, this);
    mGLSurfaceView = new GLSurfaceView(this);

    if (detectOpenGLES20()) {
        // Tell the surface view we want to create an OpenGL ES 2.0-compatible
        // context, and set an OpenGL ES 2.0-compatible renderer.
        mGLSurfaceView.setEGLContextClientVersion(2);
        pointsRenderer = new PointsRenderer(this);
        mGLSurfaceView.setRenderer(pointsRenderer);
    } else {
        // TODO: Handle as an unrecoverable error and leave the activity somehow...
    }

    // External files preparation

    InputStream in = null;
    OutputStream out = null;
    try {
        Log.d(DEBUG_TAG, "Media rady: " + isExternalStorageWritable());

        AssetManager assetManager = getAssets();
        in = assetManager.open(GALGS_CLASS_FILE);
        if (in != null) {
            galgsRubyClassesDirectory = new File(GALGS_CLASS_DIR);
            galgsRubyClassesDirectory.mkdir();
            if (!galgsRubyClassesDirectory.isDirectory()) {
                Log.d(DEBUG_TAG, "Hmm, " + galgsRubyClassesDirectory + " does not exist, trying mkdirs...");
                galgsRubyClassesDirectory.mkdirs();
            }
            File outputFile = new File(galgsRubyClassesDirectory, GALGS_CLASS_FILE);
            if (outputFile.exists()) {
                // Load from what user might have edited
                outputFile = new File(galgsRubyClassesDirectory, GALGS_CLASS_FILE + ".orig");
            }
            out = new FileOutputStream(outputFile);
            copyFile(in, out);
            in.close();
            in = null;
            out.flush();
            out.close();
            out = null;
        } else {
            Log.e("IO HELL", "Asset " + GALGS_CLASS_FILE + " not found...");
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // Stops the thing from trashing the context on pause/resume.
    mGLSurfaceView.setPreserveEGLContextOnPause(true);
    setContentView(mGLSurfaceView);

}