List of usage examples for android.content.res AssetManager open
public @NonNull InputStream open(@NonNull String fileName) throws IOException
From source file:de.appplant.cordova.emailcomposer.EmailComposerImpl.java
/** * The URI for an asset.// w w w . j av a 2 s . c o m * * @param path * The given asset path. * @param ctx * The application context. * @return * The URI pointing to the given path. */ @SuppressWarnings("ResultOfMethodCallIgnored") private Uri getUriForAssetPath(String path, Context ctx) { String resPath = path.replaceFirst("file:/", "www"); String fileName = resPath.substring(resPath.lastIndexOf('/') + 1); File dir = ctx.getExternalCacheDir(); if (dir == null) { Log.e("EmailComposer", "Missing external cache dir"); return Uri.EMPTY; } String storage = dir.toString() + ATTACHMENT_FOLDER; File file = new File(storage, fileName); new File(storage).mkdir(); try { AssetManager assets = ctx.getAssets(); FileOutputStream outStream = new FileOutputStream(file); InputStream inputStream = assets.open(resPath); copyFile(inputStream, outStream); outStream.flush(); outStream.close(); } catch (Exception e) { Log.e("EmailComposer", "File not found: assets/" + resPath); e.printStackTrace(); } return Uri.fromFile(file); }
From source file:org.protocoder.network.ProtocoderHttpServer.java
private Response sendProjectFile(String uri, String method, Properties header, Properties parms, Properties files) {/*from w w w. j a v a2 s . com*/ Response res = null; // Clean up uri uri = uri.trim().replace(File.separatorChar, '/'); MLog.d(TAG, uri); // have the object build the directory structure, if needed. AssetManager am = ctx.get().getAssets(); try { MLog.d(TAG, WEBAPP_DIR + uri); InputStream fi = am.open(WEBAPP_DIR + uri); // Get MIME type from file name extension, if possible String mime = null; int dot = uri.lastIndexOf('.'); if (dot >= 0) { mime = MIME_TYPES.get(uri.substring(dot + 1).toLowerCase()); } if (mime == null) { mime = NanoHTTPD.MIME_DEFAULT_BINARY; } res = new Response(HTTP_OK, mime, fi); } catch (IOException e) { e.printStackTrace(); MLog.d(TAG, e.getStackTrace().toString()); res = new Response(HTTP_INTERNALERROR, "text/html", "ERROR: " + e.getMessage()); } return res; }
From source file:org.protocoder.network.ProtocoderHttpServer.java
private Response sendWebAppFile(String uri, String method, Properties header, Properties parms, Properties files) {//from ww w. j a v a 2 s .c o m Response res = null; MLog.d(TAG, "" + method + " '" + uri + " " + /* header + */" " + parms); String escapedCode = parms.getProperty("code"); String unescapedCode = StringEscapeUtils.unescapeEcmaScript(escapedCode); MLog.d("HTTP Code", "" + escapedCode); MLog.d("HTTP Code", "" + unescapedCode); // Clean up uri uri = uri.trim().replace(File.separatorChar, '/'); if (uri.indexOf('?') >= 0) { uri = uri.substring(0, uri.indexOf('?')); } // We never want to request just the '/' if (uri.length() == 1) { uri = "index.html"; } // We're using assets, so we can't have a leading '/' if (uri.charAt(0) == '/') { uri = uri.substring(1, uri.length()); } // have the object build the directory structure, if needed. AssetManager am = ctx.get().getAssets(); try { MLog.d(TAG, WEBAPP_DIR + uri); InputStream fi = am.open(WEBAPP_DIR + uri); // Get MIME type from file name extension, if possible String mime = null; int dot = uri.lastIndexOf('.'); if (dot >= 0) { mime = MIME_TYPES.get(uri.substring(dot + 1).toLowerCase()); } if (mime == null) { mime = NanoHTTPD.MIME_DEFAULT_BINARY; } res = new Response(HTTP_OK, mime, fi); } catch (IOException e) { e.printStackTrace(); MLog.d(TAG, e.getStackTrace().toString()); res = new Response(HTTP_INTERNALERROR, "text/html", "ERROR: " + e.getMessage()); } return res; }
From source file:io.realm.RealmJsonTest.java
private InputStream loadJsonFromAssets(String file) { AssetManager assetManager = getContext().getAssets(); InputStream input = null;//from w w w . j a va 2 s . c om try { input = assetManager.open(file); } catch (IOException e) { throw new RuntimeException(e); } finally { return input; } }
From source file:com.sonymobile.androidapp.gridcomputing.activities.SummaryActivity.java
/** * Read Legal text from Assets.//from w ww .ja v a2 s. com * * @return Legal text as String. */ private List<String> getLegalString() { final List<String> list = new ArrayList<>(); final AssetManager assetsManager = getAssets(); BufferedReader bufferedReader = null; String line; try { final InputStream inputStream = assetsManager.open(LEGAL_FILENAME); bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")); while ((line = bufferedReader.readLine()) != null) { list.add(line); } } catch (final IOException e) { Log.e(e.getLocalizedMessage()); } finally { if (null != bufferedReader) { try { bufferedReader.close(); } catch (final IOException exception) { Log.e(exception.getLocalizedMessage()); } } } return list; }
From source file:com.facebook.FacebookActivityTestCase.java
protected File createTempFileFromAsset(String assetPath) throws IOException { InputStream inputStream = null; FileOutputStream outStream = null; try {// www .j a v a 2 s .c o m AssetManager assets = getActivity().getResources().getAssets(); inputStream = assets.open(assetPath); File outputDir = getActivity().getCacheDir(); // context being the Activity pointer File outputFile = File.createTempFile("prefix", assetPath, outputDir); outStream = new FileOutputStream(outputFile); final int bufferSize = 1024 * 2; byte[] buffer = new byte[bufferSize]; int n = 0; while ((n = inputStream.read(buffer)) != -1) { outStream.write(buffer, 0, n); } return outputFile; } finally { Utility.closeQuietly(outStream); Utility.closeQuietly(inputStream); } }
From source file:uk.co.threeonefour.android.snowball.activities.game.GameActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_game); imageView = (GraphicsView) findViewById(R.id.view_game_image); textInputView = (TextInputView) findViewById(R.id.view_game_text_input); textView = (TextView) findViewById(R.id.view_game_text_output); textScrollView = (ScrollView) findViewById(R.id.view_game_text_output_scroll); progressBar = (ProgressBar) findViewById(R.id.view_game_progressbar); imageView.setVisibility(View.INVISIBLE); textInputView.setVisibility(View.INVISIBLE); textView.setVisibility(View.INVISIBLE); textScrollView.setVisibility(View.INVISIBLE); progressBar.setVisibility(View.VISIBLE); textInputView.setTextInputHandler(this); textView.setMovementMethod(LinkMovementMethod.getInstance()); formatter = new OutputFormatter(); formatter.setWordClickedHandler(this); formatter.setTextColor(textView.getCurrentTextColor()); formatter.setHighlightDirections(true); formatter.setClickableText(true);// ww w .jav a2 s .c o m gestureDetector = new GestureDetectorCompat(this, new MyGestureListener()); graphicsHandler = new QueuedGraphicsHandler(); graphicsHandlerContext = new GraphicsContext(); level9 = new IcyVm(graphicsHandler, new MyFilehandler(), new PersistableGameStateFactory()); createTask = new AsyncTask<Void, Integer, Boolean>() { @Override protected Boolean doInBackground(Void... arg0) { try { AssetManager assetManager = getAssets(); InputStream in = assetManager.open("games/SNOWBALL.SNA"); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(in, out); level9.loadGame(out.toByteArray()); level9.startGame(); } catch (IOException e) { Log.e("game", "Failed to load file", e); } /* configure the selected game state */ Bundle extras = getIntent().getExtras(); if (extras != null) { gameStateSlot = extras.getInt(IntentConstants.GAME_STATE_SLOT, -1); } if (gameStateSlot == -1) { // TODO should never get here without a slot selected; use dao to get default slot id gameStateSlot = 0; } return true; } @Override protected void onPostExecute(Boolean result) { imageView.setVisibility(View.VISIBLE); textInputView.setVisibility(View.VISIBLE); textView.setVisibility(View.VISIBLE); textScrollView.setVisibility(View.VISIBLE); progressBar.setVisibility(View.GONE); GameState gameState = gameStateDao.loadGameState(gameStateSlot); GameStateSummary gameStateSummary = gameStateDao.loadGameStateSummary(gameStateSlot); if (gameState != null && gameStateSummary != null) { level9.setGameState(gameState); graphicsHandlerContext.setBitmap(gameStateDao.loadGraphics(gameStateSummary.getSlot())); imageView.setBitmap(graphicsHandlerContext.getBitmap()); textView.setText(""); processOutputText(gameStateSummary.getLastLocation()); // TODO hacky adding in a sneaky look because VM is not in the correct state for some reason level9.execute("look"); // TODO had to add this after putting into background task imageView.invalidate(); } else { String text = level9.getText().trim(); processOutput(text); } /* did we get a restore whilst we were initialising? */ if (restoredGameState != null) { level9.setGameState(restoredGameState); ramSaveSlots = restoredRamSaveSlots; imageView.setBitmap(restoredBitmap); gameStateSlot = restoredGameStateSlot; restoredGameState = null; restoredRamSaveSlots = null; restoredBitmap = null; restoredGameStateSlot = 0; } initialised = true; } }; createTask.execute((Void) null); }
From source file:de.geeksfactory.opacclient.OpacClient.java
public List<Library> getLibraries(ProgressCallback callback) throws IOException { AssetManager assets = getAssets(); String[] files = assets.list(ASSETS_BIBSDIR); int num = files.length; List<Library> libs = new ArrayList<>(); StringBuilder builder;/*w w w .ja v a 2 s .co m*/ BufferedReader reader; InputStream fis; String line; String json; for (int i = 0; i < num; i++) { builder = new StringBuilder(); fis = assets.open(ASSETS_BIBSDIR + "/" + files[i]); reader = new BufferedReader(new InputStreamReader(fis, "utf-8")); while ((line = reader.readLine()) != null) { builder.append(line); } fis.close(); json = builder.toString(); try { Library lib = Library.fromJSON(files[i].replace(".json", ""), new JSONObject(json)); if (!lib.getApi().equals("test") || BuildConfig.DEBUG) libs.add(lib); } catch (JSONException e) { Log.w("JSON library files", "Failed parsing library " + files[i]); e.printStackTrace(); } if (callback != null && i % 100 == 0 && i > 0) { // reporting progress for every 100 loaded files should be enough callback.publishProgress(((double) i) / num); } } return libs; }
From source file:com.slownet5.pgprootexplorer.filemanager.ui.FileManagerActivity.java
private void setupRoot() { if (alreadySetup()) { afterInitSetup(true);/*w ww. j a va 2s. co m*/ return; } final ProgressDialog dialog = new ProgressDialog(this); dialog.setIndeterminate(true); dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); dialog.setTitle("Setting up root"); dialog.setCancelable(false); ; dialog.setMax(100); final String os = SystemUtils.getSystemArchitecture(); Log.d(TAG, "setupRoot: architecture is: " + os); class Setup extends AsyncTask<Void, Integer, Boolean> { @Override protected Boolean doInBackground(Void... params) { new File(SharedData.CRYPTO_FM_PATH).mkdirs(); String filename = SharedData.CRYPTO_FM_PATH + "/toybox"; AssetManager asset = getAssets(); try { InputStream stream = asset.open("toybox"); OutputStream out = new FileOutputStream(filename); byte[] buffer = new byte[4096]; int read; int total = 0; while ((read = stream.read(buffer)) != -1) { total += read; out.write(buffer, 0, read); } Log.d(TAG, "doInBackground: total written bytes: " + total); stream.close(); out.flush(); out.close(); } catch (IOException ex) { ex.printStackTrace(); return false; } RootUtils.initRoot(filename); return true; } @Override protected void onPreExecute() { dialog.setMessage("Please wait...."); dialog.show(); } @Override protected void onPostExecute(Boolean aBoolean) { dialog.dismiss(); if (aBoolean) { SharedPreferences.Editor prefs = getSharedPreferences(CommonConstants.COMMON_SHARED_PEREFS_NAME, Context.MODE_PRIVATE).edit(); prefs.putBoolean(CommonConstants.ROOT_TOYBOX, true); prefs.apply(); prefs.commit(); afterInitSetup(true); } else { afterInitSetup(aBoolean); } } } new Setup().execute(); }