/** * Reads the raw resource as plain text from the given resource ID. * * @param context Which context to use for reading * @param rawResourceId The raw resource identifier * @return A text representation of the raw resource, never {@code null} */ @NonNull @SuppressWarnings("unused") public static String readRawResource(@NonNull final Context context, @RawRes final int rawResourceId) { InputStream inputStream = null; try { inputStream = openRawResource(context, rawResourceId); byte[] b = new byte[inputStream.available()]; // noinspection ResultOfMethodCallIgnored - don't care about number of bytes read inputStream.read(b); return new String(b); } catch (Exception e) { Log.e(TAG, "readRawResource: FAILED!", e); return ""; } finally { close(inputStream); } }
public static String loadShader(Context context, @RawRes int resId) { StringBuilder builder = new StringBuilder(); try { InputStream inputStream = context.getResources().openRawResource(resId); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) { builder.append(line) .append('\n'); } reader.close(); } catch (IOException e) { e.printStackTrace(); } return builder.toString(); }
static BitmapDrawable decodeSampledBitmapFromRes(Resources resources, @RawRes int resId, int reqWidth, int reqHeight, ImageCache cache, boolean isOpenLruCache) { final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; decodeStream(resources.openRawResource(resId), null, options); options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); // String resourceName = resources.getResourceName(resId); // if (Utils.hasHoneycomb()) { BitmapDrawable bitmapFromCache; if (isOpenLruCache) { String resourceName = resources.getResourceName(resId); bitmapFromCache = cache.getBitmapFromCache(resourceName); if (bitmapFromCache == null) { // if (Utils.hasHoneycomb()) { bitmapFromCache = readBitmapFromRes(resources, resId, cache, options); cache.addBitmap(resourceName, bitmapFromCache); } } else { bitmapFromCache = readBitmapFromRes(resources, resId, cache, options); } return bitmapFromCache; }
public static String readTextFromRawResource(final Context applicationContext, @RawRes final int resourceId) { final InputStream inputStream = applicationContext.getResources().openRawResource(resourceId); final InputStreamReader inputStreamReader = new InputStreamReader(inputStream); final BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String nextLine; final StringBuilder body = new StringBuilder(); try { while ((nextLine = bufferedReader.readLine()) != null) { body.append(nextLine); body.append('\n'); } } catch (IOException e) { return null; } return body.toString(); }
public BuiltinOfferSource(@NonNull Context context, @RawRes int rawResourceID) throws IOException { InputStream rawFileInputStream = context.getResources().openRawResource(rawResourceID); try { BufferedReader reader = new BufferedReader(new InputStreamReader(rawFileInputStream)); //Stupid Android Studio forgetting try with resources is only kitkat+ //noinspection TryFinallyCanBeTryWithResources try { StringBuilder fileContent = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { fileContent.append(line); } offersJSON = fileContent.toString(); } finally { //noinspection ThrowFromFinallyBlock reader.close(); } } finally { if (rawFileInputStream != null) { //noinspection ThrowFromFinallyBlock rawFileInputStream.close(); } } }
public void playSound(@RawRes final int resId) { if (this.mSoundSourceMap != null) { if (this.mSoundSourceMap.containsKey(Integer.valueOf(resId))) { play(((Integer) this.mSoundSourceMap.get(Integer.valueOf(resId))).intValue()); return; } this.mSoundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() { public void onLoadComplete(SoundPool soundPool, int sampleId, int status) { if (status == 0) { MQSoundPoolManager.this.mSoundSourceMap.put(Integer.valueOf(resId), Integer.valueOf(sampleId)); MQSoundPoolManager.this.play(sampleId); } } }); this.mSoundPool.load(this.mContext.getApplicationContext(), resId, 1); } }
/** * 读取图片 优先从缓存中获取图片 */ static BitmapDrawable decodeBitmapFromResLruCache(Resources resources, @RawRes int resId, int reqWidth, int reqHeight, ImageCache cache) { final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; decodeStream(resources.openRawResource(resId), null, options); options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); BitmapDrawable bitmapFromCache; String resourceName = resources.getResourceName(resId); bitmapFromCache = cache.getBitmapFromCache(resourceName); if (bitmapFromCache == null) { bitmapFromCache = readBitmapFromRes(resources, resId, cache, options); cache.addBitmapToCache(resourceName, bitmapFromCache); } return bitmapFromCache; }
/** * Load a given (html or css) resource file into a String. The input can contain tokens that will * be replaced with localised strings. * * @param substitutionTable A table of substitions, e.g. %shortMessage% -> "Error loading page..." * Can be null, in which case no substitutions will be made. * @return The file content, with all substitutions having being made. */ public static String loadResourceFile(@NonNull final Context context, @NonNull final @RawRes int resourceID, @Nullable final Map<String, String> substitutionTable) { try (final BufferedReader fileReader = new BufferedReader(new InputStreamReader(context.getResources().openRawResource(resourceID), StandardCharsets.UTF_8))) { final StringBuilder outputBuffer = new StringBuilder(); String line; while ((line = fileReader.readLine()) != null) { if (substitutionTable != null) { for (final Map.Entry<String, String> entry : substitutionTable.entrySet()) { line = line.replace(entry.getKey(), entry.getValue()); } } outputBuffer.append(line); } return outputBuffer.toString(); } catch (final IOException e) { throw new IllegalStateException("Unable to load error page data", e); } }
/** * Builds and displays a licenses fragment for you. Requires "/res/raw/licenses.html" and * "/res/layout/licenses_fragment.xml" to be present. * * @param fm A fragment manager instance used to display this LicensesFragment. */ public static void displayLicensesFragment(FragmentManager fm, @RawRes int htmlResToShow, String title) { FragmentTransaction ft = fm.beginTransaction(); Fragment prev = fm.findFragmentByTag(FRAGMENT_TAG); if (prev != null) { ft.remove(prev); } ft.addToBackStack(null); // Create and show the dialog. final DialogFragment newFragment; if (TextUtils.isEmpty(title)) { newFragment = LicensesFragment.newInstance(htmlResToShow); } else { newFragment = LicensesFragment.newInstance(htmlResToShow, title); } newFragment.show(ft, FRAGMENT_TAG); }
public static String readText(Context context, @RawRes int rawTextFileResId) { InputStream inputStream = context.getResources().openRawResource(rawTextFileResId); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); int i; try { i = inputStream.read(); while (i != -1) { byteArrayOutputStream.write(i); i = inputStream.read(); } inputStream.close(); } catch (IOException e) { e.printStackTrace(); } return byteArrayOutputStream.toString(); }
/** * Reads a raw resource text file into a String * @param context * @param resId * @return */ @Nullable public static String readTextFileFromRawResource(@NonNull final Context context, @RawRes final int resId) { final BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(context.getResources().openRawResource(resId)) ); String line; final StringBuilder body = new StringBuilder(); try { while ((line = bufferedReader.readLine()) != null) { body.append(line).append('\n'); } } catch (IOException e) { return null; } return body.toString(); }
private String loadLocalFile(@RawRes int id) { String data = null; InputStream is = null; try { is = service.getResources().openRawResource(id); byte[] buffer = new byte[is.available()]; is.read(buffer); data = new String(buffer); } catch (IOException e) { logger.e("loadLocalFile " + id, e); } finally { try { is.close(); } catch (IOException ex) { logger.e("loadLocalFile close " + id, ex); } } return data; }
/** * Initializes Embedded Social SDK. * @param application the application instance * @param configResId resource id of the JSON configuration file for the SDK * @param appKey application key */ public static void init(Application application, @RawRes int configResId, String appKey) { if (BuildConfig.DEBUG) { initLogging(application); } InputStream is = application.getResources().openRawResource(configResId); Reader reader = new InputStreamReader(is); Options options = new Gson().fromJson(reader, Options.class); if (appKey != null) { options.setAppKey(appKey); } options.verify(); GlobalObjectRegistry.addObject(options); initGlobalObjects(application, options); WorkerService.getLauncher(application).launchService(ServiceAction.BACKGROUND_INIT); // TODO: Added to main activity access token tracking // https://developers.facebook.com/docs/facebook-login/android/v2.2#access_profile }
/** * Decodes image from resource. * Returns {@link GifDrawable} if the image is an animated GIF. * Returns {@link BitmapDrawable} if the image is s valid static image {@link BitmapFactory} * can decode. * * @param res The resources object containing the image data * @param id The resource id of the image data * @param options optional options if an image will be decoded to a Bitmap * @return decoded {@link Drawable} * @throws IOException on error * @throws NullPointerException if Resources is null * @throws Resources.NotFoundException if resource under the given id does not exist */ @NonNull public static Drawable decodeResourceOrThrow(final Resources res, @DrawableRes @RawRes final int id, @Nullable final BitmapFactory.Options options) throws IOException { if (res == null) { throw new NullPointerException("Resources must not be null"); } final AssetFileDescriptor descriptor = res.openRawResourceFd(id); try { return decodeStreamOrThrow(res, descriptor.createInputStream(), null, options); } finally { descriptor.close(); } }
public void play(Context context, @RawRes int resId) { if (mMediaPlayer != null && mResId == resId) { // same file, just play again mMediaPlayer.stop(); try { mMediaPlayer.prepare(); play(); return; } catch (IOException e) { // will simply re-create the media player } } if (mMediaPlayer != null) { mMediaPlayer.release(); } mMediaPlayer = create(context, resId); if (mMediaPlayer != null) { mResId = resId; play(); } }
/** * Reads text from raw resource. * * @param resource id of raw file to read, or {@code 0}. * @return text from raw resource, or {@code null} * if reading has failed or resource is {@code 0}. */ @Nullable public static String readText(@NonNull Context context, @RawRes int resource) { if (resource == 0) return null; final InputStream inputStream = context.getResources().openRawResource(resource); final InputStreamReader inputStreamReader = new InputStreamReader(inputStream); final BufferedReader bufferedReader = new BufferedReader(inputStreamReader); try { return IOUtils.readTextFromBufferedReader(bufferedReader); } catch (IOException e) { Timber.tag(TAG).e("Failed to read raw resource: " + resource); return null; } }
private void readAndExecuteSQLScript(SQLiteDatabase db, Context context, @RawRes int sqlScriptResId) { Resources res = context.getResources(); try { InputStream is = res.openRawResource(sqlScriptResId); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); executeSQLScript(db, reader); reader.close(); is.close(); } catch (IOException e) { throw new RuntimeException("Unable to read SQL script", e); } }
/** * Reads text from raw resource. * * @param resource id of raw file to read, or {@code 0}. * @return text from raw resource, or {@code null} * if reading has failed or resource is {@code 0}. */ @Nullable public static String readText(@NonNull Context context, @RawRes int resource) { if (resource == 0) return null; final InputStream inputStream = context.getResources().openRawResource(resource); final InputStreamReader inputStreamReader = new InputStreamReader(inputStream); final BufferedReader bufferedReader = new BufferedReader(inputStreamReader); try { return FileUtils.readTextFromBufferedReader(bufferedReader); } catch (IOException e) { Log.e(TAG, "Failed to read raw resource: " + resource); return null; } }
/** * Sets the raw resource ID of video to play. * * @param id The raw resource ID. */ public void setVideoResourceId(@RawRes int id) { if (id == mVideoResourceId) { return; } mVideoResourceId = id; Surface surface = mSurfaceView.getHolder().getSurface(); if (surface != null && surface.isValid()) { closeVideo(); openVideo(surface); } }
@Override public Movie getMovie(@RawRes int id) throws NotFoundException { int realId = getCorrespondResId(id); if (realId > 0) { return mSkinResources.getMovie(realId); } return super.getMovie(id); }
@Override public InputStream openRawResource(@RawRes int id) throws NotFoundException { int realId = getCorrespondResId(id); if (realId > 0) { return mSkinResources.openRawResource(realId); } return super.openRawResource(id); }
@Override public InputStream openRawResource(@RawRes int id, TypedValue value) throws NotFoundException { int realId = getCorrespondResId(id); if (realId > 0) { return mSkinResources.openRawResource(realId, value); } return super.openRawResource(id, value); }
@Override public AssetFileDescriptor openRawResourceFd(@RawRes int id) throws NotFoundException { int realId = getCorrespondResId(id); if (realId > 0) { return mSkinResources.openRawResourceFd(realId); } return super.openRawResourceFd(id); }
public static String getRawString(@NonNull Context context, @RawRes int rawId) throws IOException { InputStream is = context.getResources().openRawResource(rawId); BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8)); StringBuilder sb = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { sb.append(line).append("\n"); } sb.deleteCharAt(sb.length() - 1); reader.close(); return sb.toString(); }
public String loadMarkdownForTextViewFromRaw(@RawRes int rawMdFile, String prepend) { try { return new SimpleMarkdownParser() .parse(_context.getResources().openRawResource(rawMdFile), prepend, SimpleMarkdownParser.FILTER_ANDROID_TEXTVIEW) .replaceColor("#000001", color(getResId(ResType.COLOR, "accent"))) .removeMultiNewlines().replaceBulletCharacter("*").getHtml(); } catch (IOException e) { e.printStackTrace(); return ""; } }
/** * Checks if given raw resource is empty or not. * * @param context Which context to use for checking * @param rawResourceId The raw resource identifier * @return {@code True} if resource is empty, {@code false} otherwise */ @SuppressWarnings("unused") public static boolean isRawResourceEmpty(@NonNull final Context context, @RawRes final int rawResourceId) { InputStream inputStream = null; try { inputStream = openRawResource(context, rawResourceId); return inputStream.available() <= 0; } catch (Exception e) { Log.e(TAG, "isRawResourceEmpty: FAILED!", e); return false; } finally { close(inputStream); } }
protected ShaderProgram(Context context, @RawRes int vertexShaderResourceId, @RawRes int fragmentShaderResourceId) { // Compile the shaders and link the program. mProgram = ShaderHelper.buildProgram( Utils.loadShader(context, vertexShaderResourceId), Utils.loadShader(context, fragmentShaderResourceId)); }
public WeaponData(@StringRes int nameRes, @DrawableRes int drawableRes, @RawRes int soundRes, int strength, int spray, int capacity) { this.nameRes = nameRes; this.drawableRes = drawableRes; this.soundRes = soundRes; this.strength = strength; this.spray = spray; this.capacity = capacity; }
static String getStringFromRawResUnsafe(final Context context, @RawRes final int rawResource) { try { return getStringFromRawRes(context, rawResource); } catch (final IOException e) { throw new IllegalStateException("Unable to String from resource: " + rawResource); // don't log exception to avoid leaking user data. } }
private void setImageFrame(Resources resources, @RawRes int[] resArray, int width, int height, int fps, OnImageLoadListener onPlayFinish) { this.width = width; this.height = height; this.resources = resources; if (imageCache == null) { imageCache = new ImageCache(); } this.onImageLoadListener = onPlayFinish; frameTime = 1000f / fps + 0.5f; workHandler.addMessageProxy(this); this.resArray = resArray; }
/** * load frame form file resources Array; * * @param resArray resources Array * @param fps The number of broadcast images per second * @param onPlayFinish finish callback */ @Deprecated public void loadImage(Resources resources, @RawRes int[] resArray, int fps, OnImageLoadListener onPlayFinish) { if (!isRunning) { setImageFrame(resources, resArray, width, height, fps, onPlayFinish); load(resArray); } }
public ResourceHandlerBuilder(@NonNull Resources resources, @NonNull @RawRes int[] resArray) { if (resArray.length == 0) { throw new IllegalArgumentException("resArray is not empty"); } this.resources = resources; this.resArray = resArray; createHandler(); }
@NonNull private static BitmapDrawable readBitmapFromRes(Resources resources, @RawRes int resId, ImageCache cache, BitmapFactory.Options options) { addInBitmapOptions(options, cache); // } // If we're running on Honeycomb or newer, try to use inBitmap. options.inJustDecodeBounds = false; return new BitmapDrawable(resources, decodeStream(resources.openRawResource(resId), null, options)); }
public static int createProgram(Context applicationContext, @RawRes int vertexSourceRawId, @RawRes int fragmentSourceRawId) { String vertexSource = readTextFromRawResource(applicationContext, vertexSourceRawId); String fragmentSource = readTextFromRawResource(applicationContext, fragmentSourceRawId); return createProgram(vertexSource, fragmentSource); }