Example usage for android.content.res Resources openRawResource

List of usage examples for android.content.res Resources openRawResource

Introduction

In this page you can find the example usage for android.content.res Resources openRawResource.

Prototype

@NonNull
public InputStream openRawResource(@RawRes int id) throws NotFoundException 

Source Link

Document

Open a data stream for reading a raw resource.

Usage

From source file:de.domjos.schooltools.helper.Helper.java

public static String readFileFromRaw(Context context, int id) {
    StringBuilder content = new StringBuilder();
    InputStream inputStream = null;
    try {/*www . j ava  2  s  .c  o m*/
        Resources resources = context.getResources();
        inputStream = resources.openRawResource(id);

        BufferedReader reader = new BufferedReader(
                new InputStreamReader(inputStream, Charset.defaultCharset()));
        String line;
        do {
            line = reader.readLine();
            if (line == null) {
                break;
            }
            content.append(line).append("\n");
        } while (true);
        reader.close();
    } catch (Exception ex) {
        Helper.printException(context, ex);
    } finally {
        try {
            if (inputStream != null) {
                inputStream.close();
            }
        } catch (Exception ex) {
            Helper.printException(context, ex);
        }
    }
    return content.toString();
}

From source file:Main.java

public static String getChannelNum(Context context) {
    Resources resources = context.getResources();
    try {/*from   ww  w. ja va 2s .  com*/
        Class<?> className = Class.forName(
                (new StringBuilder(String.valueOf(context.getPackageName()))).append(".R$raw").toString());
        Field field = className.getField("parent");
        Integer result = (Integer) field.get(className);
        InputStream num = resources.openRawResource(result);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int i = 1;
        try {
            while ((i = num.read()) != -1) {
                baos.write(i);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            resources = null;
            if (num != null) {
                try {
                    num.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return new String(baos.toByteArray());
    } catch (Exception e) {
    }
    return "0";
}

From source file:com.avapira.bobroreader.Bober.java

public static String rawJsonToString(Resources res, @RawRes int resId) {
    String name = res.getResourceName(resId);
    BufferedInputStream bis = new BufferedInputStream(res.openRawResource(resId));
    try {//from  www.  j  a  va 2 s.  c o m
        byte[] bytes = new byte[bis.available()];
        int bytesRead = bis.read(bytes);
        Log.i("Bober#rawJsonToString", String.format("Streaming raw file %s: %s bytes read", name, bytesRead));
        return new String(bytes);
    } catch (IOException e) {
        e.printStackTrace();
        return "";
    }
}

From source file:com.pdftron.pdf.utils.Utils.java

public static String copyResourceToTempFolder(Context context, int resId, boolean force, String resourceName)
        throws PDFNetException {
    if (context == null) {
        throw new PDFNetException("", 0L, "com.pdftron.pdf.PDFNet", "copyResourceToTempFolder()",
                "Context cannot be null to initialize resource file.");
    } else {/*www  .j  a  v a2s .  c om*/
        File resFile = new File(context.getFilesDir() + File.separator + "resourceName");
        if (!resFile.exists() || force) {
            File filesDir = context.getFilesDir();
            StatFs stat = new StatFs(filesDir.getPath());
            long size = (long) stat.getAvailableBlocks() * (long) stat.getBlockSize();
            if (size < 2903023L) {
                throw new PDFNetException("", 0L, "com.pdftron.pdf.PDFNet", "copyResourceToTempFolder()",
                        "Not enough space available to copy resources file.");
            }

            Resources rs = context.getResources();

            try {
                InputStream e = rs.openRawResource(resId);
                FileOutputStream fos = context.openFileOutput(resourceName, 0);
                byte[] buffer = new byte[1024];

                int read;
                while ((read = e.read(buffer)) != -1) {
                    fos.write(buffer, 0, read);
                }

                e.close();
                fos.flush();
                fos.close();

            } catch (Resources.NotFoundException var13) {
                throw new PDFNetException("", 0L, "com.pdftron.pdf.PDFNet", "initializeResource()",
                        "Resource file ID does not exist.");
            } catch (FileNotFoundException var14) {
                throw new PDFNetException("", 0L, "com.pdftron.pdf.PDFNet", "initializeResource()",
                        "Resource file not found.");
            } catch (IOException var15) {
                throw new PDFNetException("", 0L, "com.pdftron.pdf.PDFNet", "initializeResource()",
                        "Error writing resource file to internal storage.");
            } catch (Exception var16) {
                throw new PDFNetException("", 0L, "com.pdftron.pdf.PDFNet", "initializeResource()",
                        "Unknown error.");
            }
        }

        return context.getFilesDir().getAbsolutePath();
    }
}

From source file:org.kavaproject.kavatouch.internal.JSONDeviceConfiguration.java

public JSONDeviceConfiguration(Resources resources, int id) {
    InputStream jsonStream = resources.openRawResource(id);
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    int ctr;/*from   w  ww .j  a  v a 2  s  . c o  m*/
    try {
        ctr = jsonStream.read();
        while (ctr != -1) {
            byteArrayOutputStream.write(ctr);
            ctr = jsonStream.read();
        }
        jsonStream.close();
    } catch (IOException e) {
        throw new Error(e);
    }
    try {
        JSONObject jConfiguration = new JSONObject(byteArrayOutputStream.toString());
        flipYAxis = jConfiguration.getBoolean("flipYAxis");
        useIPadTheme = jConfiguration.getBoolean("useIPadTheme");
        JSONArray jDeviceModifiers = jConfiguration.getJSONArray("deviceModifiers");
        for (int i = 0; i < jDeviceModifiers.length(); i++) {
            deviceModifiers.add(jDeviceModifiers.getString(i));
        }
        JSONArray jImageScaleModifiers = jConfiguration.getJSONArray("imageScaleModifiers");
        for (int i = 0; i < jImageScaleModifiers.length(); i++) {
            imageScaleModifiers.add(ImageScaleModifier.createFromJSON(jImageScaleModifiers.getJSONObject(i)));
        }
        double scale = jConfiguration.optDouble("scale");
        if (Double.isNaN(scale)) {
            DisplayMetrics displayMetrics = resources.getDisplayMetrics();
            this.scale = displayMetrics.density;
        } else {
            this.scale = (float) scale;
        }
    } catch (JSONException e) {
        throw new Error(e);
    }
}

From source file:me.willeponken.opendoor.AboutActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_about);
    TextView aboutTitle = (TextView) findViewById(R.id.textViewAboutTitle);
    aboutTitle.setText(getString(R.string.general_app_name) + " " + BuildConfig.VERSION_NAME);
    aboutTitle.setOnClickListener(new View.OnClickListener() {
        @Override//from   w w  w.ja  v a  2  s . c  om
        public void onClick(View v) {
            onClickCount++;
            if (onClickCount >= 5) {
                onClickCount = 0;
                playEpicSaxGuy();
            }
        }
    });

    TextView licenseText = (TextView) findViewById(R.id.textViewAboutLicense);
    try {
        Resources resources = this.getResources();
        InputStream reader = resources.openRawResource(R.raw.license);

        byte[] bytes = new byte[reader.available()];
        if (reader.read(bytes) <= 0) {
            throw new IOException("Failed to read any data from file");
        }
        licenseText.setText(new String(bytes));
    } catch (IOException e) {
        licenseText.setText(getString(R.string.about_activity_error_no_license));
    }
}

From source file:net.sf.sprockets.database.sqlite.DbOpenHelper.java

/**
 * Execute the statements in the resource script on the database. Each statement must end with a
 * semicolon./*from   w ww  .j av a 2 s .  c o  m*/
 */
private void execScript(SQLiteDatabase db, Resources res, int script) throws IOException {
    LineIterator lines = IOUtils.lineIterator(res.openRawResource(script), UTF_8);
    StringBuilder sql = new StringBuilder(2048); // enough capacity for a long statement
    try { // read each (potentially multi-line) statement and execute them one at a time
        while (lines.hasNext()) {
            String line = lines.next().trim();
            int length = line.length();
            if (length > 0) {
                sql.append(line).append("\n");
                if (line.charAt(length - 1) == ';') { // statement loaded
                    db.execSQL(sql.toString());
                    sql.setLength(0); // reset builder for a new statement
                }
            }
        }
    } finally {
        lines.close();
    }
}

From source file:fi.aalto.trafficsense.trafficsense.ui.AboutActivity.java

private void loadAndFillField(int resId, TextView field) {
    Resources res = getResources();

    if (res == null || field == null)
        return;/*from   ww w  . ja va2s. c  om*/

    try {
        InputStream stream = res.openRawResource(resId);
        byte[] b = new byte[stream.available()];
        stream.read(b);
        field.setText(new String(b));
    } catch (IOException e) {
        field.setText(R.string.not_available);
    }
}

From source file:com.appnexus.opensdk.MRAIDImplementation.java

String getMraidDotJS(Resources r) {
    InputStream ins = r.openRawResource(R.raw.mraid);
    try {/* w ww  . j a  va 2  s  .  c  o  m*/
        byte[] buffer = new byte[ins.available()];
        if (ins.read(buffer) > 0) {
            return new String(buffer, "UTF-8");
        }
    } catch (IOException e) {

    }
    return null;
}

From source file:org.lumicall.android.sip.RegisterAccount.java

private String getCountryCode(String countrySymbol) {

    try {/*from   w w w  .  j ava 2  s  . c om*/
        CSVReader csv = new CSVReader(CountryData.class,
                new Class[] { String.class, String.class, String.class });

        Resources res = getResources();
        InputStream i = res.openRawResource(R.raw.country_codes);
        BufferedReader in = new BufferedReader(new InputStreamReader(i));
        CountryData cd = (CountryData) csv.read(in);
        while (cd != null) {
            if (countrySymbol.toUpperCase().equals(cd.getIsoCountryCode().toUpperCase()))
                return cd.getItuCountryCode();
            cd = (CountryData) csv.read(in);
        }
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    // TODO: log not found      
    return "";
}