Example usage for android.content Context openFileInput

List of usage examples for android.content Context openFileInput

Introduction

In this page you can find the example usage for android.content Context openFileInput.

Prototype

public abstract FileInputStream openFileInput(String name) throws FileNotFoundException;

Source Link

Document

Open a private file associated with this Context's application package for reading.

Usage

From source file:it.mb.whatshare.SendToGCMActivity.java

/**
 * Loads the ID and name of the paired device in use to share content when
 * Whatsapp is not installed on this device.
 * /*from   ww  w  .ja v  a 2  s.c o  m*/
 * @param activity
 *            the calling activity
 * @return the device loaded from file if any is configured,
 *         <code>null</code> otherwise
 * @throws OptionalDataException
 * @throws ClassNotFoundException
 * @throws IOException
 */
static Pair<PairedDevice, String> loadOutboundPairing(Context activity)
        throws OptionalDataException, ClassNotFoundException, IOException {
    FileInputStream fis = activity.openFileInput("pairing");
    Scanner scanner = new Scanner(fis).useDelimiter("\\Z");
    JSONObject json;
    try {
        json = new JSONObject(scanner.next());
        String name = json.getString("name");
        String type = json.getString("type");
        String assignedID = json.getString("assignedID");
        return new Pair<PairedDevice, String>(new PairedDevice(assignedID, name, type), assignedID);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.cssweb.android.common.CssIniFile.java

public static String loadIni(Context context, int parmInt, String key) {
    String str = null;//from  ww  w  . j a  v a2 s  . c  o  m
    Properties properties = new Properties();
    try {
        FileInputStream stream = context.openFileInput(GetFileName(parmInt));
        properties.load(stream);
        Object obj = properties.get(key);
        if (obj != null)
            str = obj.toString();
        stream.close();
    } catch (FileNotFoundException e) {

    } catch (IOException e) {

    }
    return str;
}

From source file:org.rapidandroid.ApplicationGlobals.java

/**
 * // w w w . j  ava 2  s  .  com
 */
public static JSONObject loadSettingsFromFile(Context context) {
    FileInputStream fin = null;
    InputStreamReader irdr = null;
    JSONObject readobject = null;
    try {

        fin = context.openFileInput(SETTINGS_FILE);

        irdr = new InputStreamReader(fin); // promote

        int size = (int) fin.getChannel().size();
        char[] data = new char[size]; // allocate char array of right
        // size
        irdr.read(data, 0, size); // read into char array
        irdr.close();

        String contents = new String(data);
        readobject = new JSONObject(contents);

        if (!readobject.has(KEY_ACTIVE_ALL)) {
            //dmyung hack to keep compatability with new version
            readobject.put(KEY_ACTIVE_ALL, false);
        }

        if (!readobject.has(KEY_ACTIVE_LOGGING)) {
            //dmyung hack to keep compatability with new version
            readobject.put(KEY_ACTIVE_LOGGING, false);
        }

        //         mParseCheckbox.setChecked(readobject.getBoolean(KEY_PARSE_REPLY));
        //         mParseReplyText.setText(readobject.getString(KEY_PARSE_REPLY_TEXT));
        //         mNoparseCheckBox.setChecked(readobject.getBoolean(KEY_FAILED_REPLY));
        //         mNoparseReplyText.setText(readobject.getString(KEY_FAILED_REPLY_TEXT));

    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        try {
            if (irdr != null) {
                irdr.close();
            }
            if (fin != null) {
                fin.close();
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    return readobject;
}

From source file:com.cssweb.android.common.CssIniFile.java

public static String loadStockData(Context context, String filename) {
    FileInputStream fileIn = null;
    InputStreamReader in = null;//from w ww .  j  av a  2s  . c  o m
    BufferedReader buffer = null;
    StringBuffer text = new StringBuffer();
    String res = null;
    try {
        fileIn = context.openFileInput(filename + ".dat");
        in = new InputStreamReader(fileIn);
        buffer = new BufferedReader(in);
        while ((res = buffer.readLine()) != null) {
            text.append(res);
        }
        res = text.toString();
    } catch (FileNotFoundException e) {
        //e.printStackTrace();
        res = null;
    } catch (IOException e) {
        //e.printStackTrace();
        res = null;
    } finally {
        try {
            if (fileIn != null)
                fileIn.close();
        } catch (IOException e) {
        }
        try {
            if (in != null)
                in.close();
        } catch (IOException e) {
        }
        try {
            if (buffer != null)
                buffer.close();
        } catch (IOException e) {
        }
    }
    return res;
}

From source file:com.ibm.pi.beacon.PIBeaconSensor.java

private static PIAPIAdapter retrievePIAPIAdapter(Context context) {
    PIAPIAdapter adapter = null;/*from  w  w w  . ja va  2s . co  m*/
    ObjectInputStream adapterStream = null;
    try {
        adapterStream = new ObjectInputStream(context.openFileInput("piapiadapter.data"));
        adapter = (PIAPIAdapter) adapterStream.readObject();
    } catch (IOException | ClassNotFoundException e) {
        e.printStackTrace();
    } finally {
        if (adapterStream != null) {
            try {
                adapterStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return adapter;
}

From source file:com.aegiswallet.utils.BasicUtils.java

public static JSONObject parseJSONData(Context context, String fileName) {
    String JSONString = null;//from   w ww .j a  va2  s. com
    JSONObject JSONObject = null;
    try {

        //open the inputStream to the file
        InputStream inputStream = context.openFileInput(fileName);

        int sizeOfJSONFile = inputStream.available();

        //array that will store all the data
        byte[] bytes = new byte[sizeOfJSONFile];

        //reading data into the array from the file
        inputStream.read(bytes);

        //close the input stream
        inputStream.close();

        JSONString = new String(bytes, "UTF-8");
        JSONObject = new JSONObject(JSONString);

    } catch (IOException ex) {
        ex.printStackTrace();
        return null;
    } catch (JSONException x) {
        return null;
    }
    return JSONObject;
}

From source file:pt.ubi.di.pdm.swipe.CollectionDemoActivity.java

public static String readFromFile(String filename, Context ctx) {
    FileInputStream fis = null;//w w w .  j  av  a 2 s .c o m
    String str = "";
    try {
        fis = ctx.openFileInput(filename);
        byte[] buffer = new byte[(int) fis.getChannel().size()];
        fis.read(buffer);

        for (byte b : buffer)
            str += (char) b;

        Log.i("TAG", String.format("GOT: [%s]", str));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (fis != null)
                fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return str;
    }
}

From source file:pt.ubi.di.pdm.swipe.CollectionDemoActivity.java

public static String ReadBtn(Context ctx, String file) {
    //reading text from file
    InputStreamReader InputRead = null;
    String s = "";
    try {// www.j a  v  a 2s.c  o  m
        FileInputStream fileIn = ctx.openFileInput(file);
        InputRead = new InputStreamReader(fileIn);

        char[] inputBuffer = new char[100];

        int charRead;

        while ((charRead = InputRead.read(inputBuffer)) > 0) {
            // char to string conversion
            String readstring = String.copyValueOf(inputBuffer, 0, charRead);
            s += readstring;
        }

        //Toast.makeText(ctx, s,Toast.LENGTH_SHORT).show();

    } catch (Exception e) {
        Toast.makeText(ctx, "Nao consegui carregar ficheiro", Toast.LENGTH_SHORT).show();
        //e.printStackTrace();
    } finally {
        if (InputRead != null) {
            try {
                InputRead.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return s;
    }
}

From source file:org.protocoderrunner.utils.FileIO.java

/**
 * Read the contents of the file indicated by fileName
 *//*from w  ww  .  j a  va2s .  com*/
public static String read(Context activity, String fileName) throws IOException {
    if (fileName.contains("/0/")) {
        fileName = fileName.replace("/0/", "/legacy/");
    }
    FileInputStream is = activity.openFileInput(fileName);
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();
    while (br.ready()) {
        String line = br.readLine();
        sb.append(line);
    }
    String data = sb.toString();
    return data;
}

From source file:org.wso2.emm.agent.utils.CommonUtils.java

/**
 * Generates keys, CSR and certificates for the devices.
 * @param context - Application context.
 * @param listener - DeviceCertCreationListener which provide device .
 *//*w ww.ja v a 2s  .com*/
public static void generateDeviceCertificate(final Context context, final DeviceCertCreationListener listener)
        throws AndroidAgentException {

    if (context.getFileStreamPath(Constants.DEVICE_CERTIFCATE_NAME).exists()) {
        try {
            listener.onDeviceCertCreated(
                    new BufferedInputStream(context.openFileInput(Constants.DEVICE_CERTIFCATE_NAME)));
        } catch (FileNotFoundException e) {
            Log.e(TAG, e.getMessage());
        }
    } else {

        try {
            ServerConfig utils = new ServerConfig();
            final KeyPair deviceKeyPair = KeyPairGenerator.getInstance(Constants.DEVICE_KEY_TYPE)
                    .generateKeyPair();
            X500Principal subject = new X500Principal(Constants.DEVICE_CSR_INFO);
            PKCS10CertificationRequest csr = new PKCS10CertificationRequest(Constants.DEVICE_KEY_ALGO, subject,
                    deviceKeyPair.getPublic(), null, deviceKeyPair.getPrivate());

            EndPointInfo endPointInfo = new EndPointInfo();
            endPointInfo.setHttpMethod(org.wso2.emm.agent.proxy.utils.Constants.HTTP_METHODS.POST);
            endPointInfo.setEndPoint(utils.getAPIServerURL(context) + Constants.SCEP_ENDPOINT);
            endPointInfo.setRequestParams(Base64.encodeToString(csr.getEncoded(), Base64.DEFAULT));

            new APIController().invokeAPI(endPointInfo, new APIResultCallBack() {
                @Override
                public void onReceiveAPIResult(Map<String, String> result, int requestCode) {
                    try {
                        CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
                        InputStream in = new ByteArrayInputStream(
                                Base64.decode(result.get("response"), Base64.DEFAULT));
                        X509Certificate cert = (X509Certificate) certFactory.generateCertificate(in);
                        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                        KeyStore keyStore = KeyStore.getInstance("PKCS12");
                        keyStore.load(null);
                        keyStore.setKeyEntry(Constants.DEVICE_CERTIFCATE_ALIAS,
                                (Key) deviceKeyPair.getPrivate(),
                                Constants.DEVICE_CERTIFCATE_PASSWORD.toCharArray(),
                                new java.security.cert.Certificate[] { cert });
                        keyStore.store(byteArrayOutputStream,
                                Constants.DEVICE_CERTIFCATE_PASSWORD.toCharArray());
                        FileOutputStream outputStream = context.openFileOutput(Constants.DEVICE_CERTIFCATE_NAME,
                                Context.MODE_PRIVATE);
                        outputStream.write(byteArrayOutputStream.toByteArray());
                        byteArrayOutputStream.close();
                        outputStream.close();
                        try {
                            listener.onDeviceCertCreated(new BufferedInputStream(
                                    context.openFileInput(Constants.DEVICE_CERTIFCATE_NAME)));
                        } catch (FileNotFoundException e) {
                            Log.e(TAG, e.getMessage());
                        }
                    } catch (CertificateException e) {
                        Log.e(TAG, e.getMessage());
                    } catch (KeyStoreException e) {
                        e.printStackTrace();
                    } catch (NoSuchAlgorithmException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }, Constants.SCEP_REQUEST_CODE, context, true);

        } catch (NoSuchAlgorithmException e) {
            throw new AndroidAgentException("No algorithm for key generation", e);
        } catch (SignatureException e) {
            throw new AndroidAgentException("Invalid Signature", e);
        } catch (NoSuchProviderException e) {
            throw new AndroidAgentException("Invalid provider", e);
        } catch (InvalidKeyException e) {
            throw new AndroidAgentException("Invalid key", e);
        }

    }

}