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:org.xwalk.runtime.extension.XWalkExtensionManager.java

private String getAssetsFileContent(AssetManager assetManager, String fileName) throws IOException {
    String result = "";
    InputStream inputStream = null;
    try {/*from  ww  w. jav  a 2s. c  o m*/
        inputStream = assetManager.open(fileName);
        int size = inputStream.available();
        byte[] buffer = new byte[size];
        inputStream.read(buffer);
        result = new String(buffer);
    } finally {
        if (inputStream != null) {
            inputStream.close();
        }
    }
    return result;
}

From source file:run.ace.NativeHost.java

byte[] readXbf(String uri) throws IOException {
    Context context = _activity.getApplicationContext();
    AssetManager am = context.getAssets();
    InputStream is = am.open(uri);

    ByteArrayOutputStream buffer = new ByteArrayOutputStream();

    int numRead;//from   w ww. j a  v a 2s .com
    byte[] data = new byte[16384];
    while ((numRead = is.read(data, 0, data.length)) != -1) {
        buffer.write(data, 0, numRead);
    }
    buffer.flush();

    return buffer.toByteArray();
}

From source file:com.precisionag.waterplane.MainActivity.java

private void readDataFile(Field field) {
    try {/*from ww  w.j  a v a2 s.c o m*/

        //read data from string
        AssetManager am = getApplicationContext().getAssets();
        BufferedReader dataIO = new BufferedReader(new InputStreamReader(am.open("field.latlng")));
        String dataString = null;

        dataString = dataIO.readLine();
        double north = Double.parseDouble(dataString);
        dataString = dataIO.readLine();
        double east = Double.parseDouble(dataString);
        dataString = dataIO.readLine();
        double south = Double.parseDouble(dataString);
        dataString = dataIO.readLine();
        double west = Double.parseDouble(dataString);

        LatLng northEast = new LatLng(north, east);
        LatLng southWest = new LatLng(south, west);

        dataString = dataIO.readLine();
        double minElevation = Double.parseDouble(dataString);
        dataString = dataIO.readLine();
        double maxElevation = Double.parseDouble(dataString);

        //set corresponding parameters in field
        field.setBounds(new LatLngBounds(northEast, southWest));
        field.setNortheast(northEast);
        field.setSouthwest(southWest);
        field.setMinElevation(minElevation);
        field.setMaxElevation(maxElevation);

        dataIO.close();

    } catch (IOException e) {
    }

}

From source file:com.javielinux.utils.Utils.java

public static String getAsset(Context cnt, String file) {
    AssetManager assetManager = cnt.getAssets();
    InputStream inputStream = null;
    try {/* www.  j  a  v  a2s  .  co  m*/
        inputStream = assetManager.open(file);
    } catch (IOException e) {
        Log.d(TAG, "No se ha podido cargar el fichero " + file);
    }

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    byte buf[] = new byte[1024];
    int len;
    try {
        while ((len = inputStream.read(buf)) != -1) {
            outputStream.write(buf, 0, len);
        }
        outputStream.close();
        inputStream.close();
    } catch (IOException e) {
    }
    return outputStream.toString();
}

From source file:com.duy.ascii.sharedcode.bigtext.BigFontFragment.java

private void createPresenter() {
    if (mPresenter != null)
        return;//from  ww w  .j a v a  2s .  c om
    try {
        AssetManager assets = getContext().getAssets();
        String[] names = assets.list("bigtext");
        InputStream[] inputStreams = new InputStream[names.length];
        for (int i = 0; i < names.length; i++) {
            String name = names[i];
            inputStreams[i] = assets.open("bigtext" + "/" + name);
        }
        mPresenter = new BigFontPresenter(inputStreams, this);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

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

private HttpUriRequest createFileSendRequest() throws IOException {
    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");

    AssetManager manager = getApplicationContext().getAssets();
    InputStream in = null;/*  w w  w .j av  a  2  s  .  c o  m*/
    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);
        return request;
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:ar.com.lapotoca.resiliencia.gallery.ui.ImageDetailActivity.java

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.image_menu, menu);
    MenuItem shareItem = menu.findItem(R.id.menu_share);
    shareItem.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
        @Override/*from ww  w  .  jav a 2s .  c  o m*/
        public boolean onMenuItemClick(MenuItem item) {
            try {

                ImageHolder img = Images.image[mPager.getCurrentItem()];
                if (img == null) {
                    return false;
                }

                AnalyticsHelper.getInstance().sendImageShareEvent(img.getUrl());

                Uri bmpUri;
                if (img.isLocal()) {
                    bmpUri = Uri.parse("content://" + AssetProvider.CONTENT_URI + "/" + img.getUrl());
                } else {
                    ImageView iv = (ImageView) findViewById(R.id.picImageView);
                    bmpUri = getLocalBitmapUri(iv);
                }
                if (bmpUri != null) {
                    Intent shareIntent = new Intent();
                    shareIntent.setAction(Intent.ACTION_SEND);
                    shareIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
                    shareIntent.setType("image/*");
                    startActivity(Intent.createChooser(shareIntent, getString(R.string.share_item)));

                    AnalyticsHelper.getInstance().sendImageShareCompleted();
                    return true;
                } else {

                    AnalyticsHelper.getInstance().sendImageShareCanceled();
                    return false;
                }
            } catch (Exception e) {
                AnalyticsHelper.getInstance().sendImageShareFailed(e.getMessage());
                return false;
            }
        }
    });

    MenuItem downloadItem = menu.findItem(R.id.download_asset);
    downloadItem.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem item) {

            Context context = ImageDetailActivity.this;

            String appDirectoryName = context.getString(R.string.app_name);
            File imageRoot = new File(
                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                    appDirectoryName);

            ImageHolder img = Images.image[mPager.getCurrentItem()];
            if (img == null) {
                return false;
            }

            AssetManager assetManager = context.getAssets();
            try {
                InputStream is = assetManager.open(img.getUrl());
                String fileName = img.getUrl().split("/")[1];

                imageRoot.mkdirs();
                File image = new File(imageRoot, fileName);

                byte[] buffer = new byte[BUFFER_LENGHT];
                FileOutputStream fos = new FileOutputStream(image);
                int read = 0;

                while ((read = is.read(buffer, 0, 1024)) >= 0) {
                    fos.write(buffer, 0, read);
                }

                fos.flush();
                fos.close();
                is.close();

                String[] paths = { image.getAbsolutePath() };

                MediaScannerConnection.scanFile(context, paths, null, null);
                NotificationHelper.showNotification(context,
                        context.getString(R.string.download_image_succesfull));
                AnalyticsHelper.getInstance().sendDownloadImage(fileName);

            } catch (Exception e) {
                NotificationHelper.showNotification(context,
                        context.getString(R.string.download_no_permissions));
                AnalyticsHelper.getInstance().sendImageDownloadFailed(e.getMessage());
            }

            return true;
        }
    });

    return true;
}

From source file:com.HskPackage.HskNamespace.HSK1ProjectActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);/*www .  j a  v  a 2  s  .  c om*/

    final TextView codice = (TextView) findViewById(R.id.codice);
    final Button carattere = (Button) findViewById(R.id.carattere);
    final TextView fonetica = (TextView) findViewById(R.id.fonetica);
    final TextView significato = (TextView) findViewById(R.id.significato);

    /*********** CREATE A DATABASE ******************************************************/
    final String DB_PATH = "/data/data/com.HskPackage.HskNamespace/";
    final String DB_NAME = "chineseX.db";
    SQLiteDatabase db = null;

    boolean exists = (new File(DB_PATH + DB_NAME)).exists();

    AssetManager assetManager = getAssets();

    if (!exists) {
        try {
            InputStream in = assetManager.open(DB_NAME);
            OutputStream out = new FileOutputStream(DB_PATH + DB_NAME);
            copyFile(in, out);
            in.close();
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        File dbFile = new File(DB_PATH + DB_NAME);
        db = SQLiteDatabase.openOrCreateDatabase(dbFile, null);
    } else {
        File dbFile = new File(DB_PATH + DB_NAME);
        db = SQLiteDatabase.openOrCreateDatabase(dbFile, null);
    }

    final Integer valore = 1;
    //String query = "SELECT * FROM chineseX";
    String query = "SELECT * FROM chineseX where _id = ? ";
    String[] selectionArgs = { valore.toString() };
    Cursor cursor = null;
    cursor = db.rawQuery(query, selectionArgs);
    //cursor = db.rawQuery(query, null);
    int count = cursor.getCount();
    System.out.println("il numero di dati contenuti nel database " + count);
    while (cursor.moveToNext()) {
        long id = cursor.getLong(0);
        System.out.println("Questo  l'ID ====>" + id);
        scodice = cursor.getString(1);
        codice.setText(scodice);
        System.out.println("Questo  il codice ====>" + codice);
        scarattere = cursor.getString(2);
        carattere.setText(scarattere);
        System.out.println("Questo  il carattere ====>" + carattere);
        sfonetica = cursor.getString(3);
        fonetica.setText(sfonetica);
        System.out.println("Questo  il fonet ====>" + fonetica);

        ssignificato = cursor.getString(4);
        significato.setText("?? - Visualizza Significato");
        System.out.println("Questo  il carattere ====>" + ssignificato);
    }
    //fine
    db.close();

    //set up sound button
    final MediaPlayer mpButtonClick = MediaPlayer.create(this, R.raw.hangout_ringtone);

    //final MediaPlayer chword001 = MediaPlayer.create(this, R.raw.ayi001);

    /*
                    
            // set up change Images 
                    
            miaImmagine = (ImageView) findViewById(R.id.Image); 
            // dichiaro  l'oggetto image view
                 
            miaImmagine.setImageResource(R.drawable.uno1);
            // associo l'immagine alla  figura uno
               
            // setto un evento di cattura del click sull'immagine
            miaImmagine.setOnClickListener( new OnClickListener() 
            {
                public void onClick(View arg0) {
                   //chword001.start();
                }       
            }) ;
          */

    final Intent first = new Intent(this, Activity2.class);
    final Intent immagine = new Intent(this, Activity3.class);

    /*
     * Un intent  definito nella javadoc della classe android.content.Intent come una 
     * "descrizione astratta dell'operazione da eseguire".
     * E un intent ESPLICITO perch cosciamo il destinatario.
     * Passiamo come parametri il context attuale ed la classe che identifica l'activity di destinazione.
     * E' importante che la classe sia registrata nell'AndroidManifest.xml
     * */

    Button b = (Button) this.findViewById(R.id.button1);
    Button b2 = (Button) this.findViewById(R.id.button2);
    Button b3 = (Button) this.findViewById(R.id.carattere);

    b.setOnClickListener(new OnClickListener() {
        public void onClick(View arg0) {
            Integer valore = 1;
            valore = valore + 1;
            if (valore >= 153) {
                valore = 1;
            }

            System.out.println("AVANTI" + valore);
            first.putExtra("AVANTI", valore);
            startActivity(first);
            finish();
            mpButtonClick.start();
        }
    });

    b2.setOnClickListener(new OnClickListener() {
        public void onClick(View arg0) {

            Integer valore = 153;

            System.out.println("AVANTI == >" + valore);
            first.putExtra("AVANTI", valore);
            startActivity(first);
            finish();
            mpButtonClick.start();
        }
    });

    b3.setOnClickListener(new OnClickListener() {

        public void onClick(View arg0) {

            Integer valore = 1;

            System.out.println("AVANTI" + valore);

            immagine.putExtra("AVANTI", valore);

            startActivity(immagine);
            finish();
            mpButtonClick.start();
        }
    });
}

From source file:com.mindprotectionkit.freephone.signaling.SignalingSocket.java

private Socket constructSSLSocket(Context context, String host, int port) throws SignalingException {
    try {// ww  w  . j  a v a 2  s .c  o m
        AssetManager assetManager = context.getAssets();
        InputStream keyStoreInputStream = assetManager.open("whisper.store");
        KeyStore trustStore = KeyStore.getInstance("BKS");

        trustStore.load(keyStoreInputStream, "whisper".toCharArray());

        SSLSocketFactory sslSocketFactory = new SSLSocketFactory(trustStore);

        if (Release.SSL) {
            sslSocketFactory.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
        } else {
            Log.w("SignalingSocket", "Disabling hostname verification...");
            sslSocketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        }

        return timeoutHackConnect(sslSocketFactory, host, port);
    } catch (IOException ioe) {
        throw new SignalingException(ioe);
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalArgumentException(e);
    } catch (KeyStoreException e) {
        throw new IllegalArgumentException(e);
    } catch (CertificateException e) {
        throw new IllegalArgumentException(e);
    } catch (KeyManagementException e) {
        throw new IllegalArgumentException(e);
    } catch (UnrecoverableKeyException e) {
        throw new IllegalArgumentException(e);
    }
}

From source file:com.orange.ocara.tools.AssetsHelper.java

/**
 * Copy the asset at the specified path to this app's data directory. If the
 * asset is a directory, its contents are also copied.
 *///  w w  w.j  a v  a2s.  com
public static void copyAsset(AssetManager assetManager, String rootPath, String path, File targetFolder)
        throws IOException {

    String fullPath = StringUtils.isEmpty(path) ? rootPath : rootPath + File.separator + path;

    // If we have a directory, we make it and recurse. If a file, we copy its
    // contents.
    try {
        String[] contents = assetManager.list(fullPath);

        // The documentation suggests that list throws an IOException, but doesn't
        // say under what conditions. It'd be nice if it did so when the path was
        // to a file. That doesn't appear to be the case. If the returned array is
        // null or has 0 length, we assume the path is to a file. This means empty
        // directories will get turned into files.
        if (contents == null || contents.length == 0) {
            throw new IOException();
        }

        // Recurse on the contents.
        for (String entry : contents) {
            String newPath = StringUtils.isEmpty(path) ? entry : path + File.separator + entry;

            copyAsset(assetManager, rootPath, newPath, targetFolder);
        }
    } catch (IOException e) {

        File file = new File(targetFolder, path);

        if (file.getParentFile() != null) {
            file.getParentFile().mkdirs();
        }

        FileUtils.copyInputStreamToFile(assetManager.open(fullPath), file);
    }
}