Example usage for android.content Context openFileOutput

List of usage examples for android.content Context openFileOutput

Introduction

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

Prototype

public abstract FileOutputStream openFileOutput(String name, @FileMode int mode) throws FileNotFoundException;

Source Link

Document

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

Usage

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 {/*from   w w w  .j a  va 2  s.  c o  m*/
        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:br.com.carlosrafaelgn.fplay.list.RadioStationList.java

private void saveFavoritesInternal(Context context) throws IOException {
    FileOutputStream fs = null;/*  w w w .ja  v a  2  s .  com*/
    BufferedOutputStream bs = null;
    try {
        final int count = Math.min(MAX_COUNT, favorites.size());
        int i = 0;
        fs = context.openFileOutput("_RadioFav", 0);
        bs = new BufferedOutputStream(fs, 4096);
        Serializer.serializeInt(bs, 0x0100);
        Serializer.serializeInt(bs, count);
        for (RadioStation s : favorites) {
            if (i >= count)
                break;
            s.serialize(bs);
            i++;
        }
        bs.flush();
    } finally {
        try {
            if (bs != null)
                bs.close();
        } catch (Throwable ex) {
        }
        try {
            if (fs != null)
                fs.close();
        } catch (Throwable ex) {
        }
    }
}

From source file:net.sf.xfd.provider.PublicProvider.java

private static @Nullable Key getSalt(Context c) {
    if (cookieSalt == null) {
        synchronized (PublicProvider.class) {
            if (cookieSalt == null) {
                try {
                    try (ObjectInputStream oos = new ObjectInputStream(c.openFileInput(COOKIE_FILE))) {
                        cookieSalt = (Key) oos.readObject();
                    } catch (ClassNotFoundException | IOException e) {
                        LogUtil.logCautiously("Unable to read key file, probably corrupted or missing", e);

                        final File corrupted = c.getFileStreamPath(COOKIE_FILE);

                        //noinspection ResultOfMethodCallIgnored
                        corrupted.delete();
                    }/*from   w w  w  . j  a v a2 s. c o m*/

                    if (cookieSalt != null) {
                        return cookieSalt;
                    }

                    final KeyGenerator keygen = KeyGenerator.getInstance("HmacSHA1");
                    keygen.init(COOKIE_SIZE * Byte.SIZE);

                    cookieSalt = keygen.generateKey();

                    try (ObjectOutputStream oos = new ObjectOutputStream(
                            c.openFileOutput(COOKIE_FILE, Context.MODE_PRIVATE))) {
                        oos.writeObject(cookieSalt);
                    } catch (IOException e) {
                        LogUtil.logCautiously("Failed to save key file", e);

                        return null;
                    }
                } catch (NoSuchAlgorithmException e) {
                    throw new AssertionError("failed to initialize hash functions", e);
                }
            }
        }
    }

    return cookieSalt;
}

From source file:com.apptentive.android.sdk.model.FileMessage.java

/**
 * This method stores an image, and compresses it in the process so it doesn't fill up the disk. Therefore, do not use
 * it to store an exact copy of the file in question.
 */// ww  w . ja  v a  2s. c  o m
public boolean internalCreateStoredImage(Context context, String uriString) {
    Uri uri = Uri.parse(uriString);

    ContentResolver resolver = context.getContentResolver();
    String mimeType = resolver.getType(uri);
    MimeTypeMap mime = MimeTypeMap.getSingleton();
    String extension = mime.getExtensionFromMimeType(mimeType);
    setFileName(uri.getLastPathSegment() + "." + extension);
    setMimeType(mimeType);

    // Create a file to save locally.
    String localFileName = getStoredFileId();
    File localFile = new File(localFileName);

    // Copy the file contents over.
    InputStream is = null;
    CountingOutputStream cos = null;
    try {
        is = new BufferedInputStream(context.getContentResolver().openInputStream(uri));
        cos = new CountingOutputStream(
                new BufferedOutputStream(context.openFileOutput(localFile.getPath(), Context.MODE_PRIVATE)));
        System.gc();
        Bitmap smaller = ImageUtil.createScaledBitmapFromStream(is, MAX_STORED_IMAGE_EDGE,
                MAX_STORED_IMAGE_EDGE, null);
        // TODO: Is JPEG what we want here?
        smaller.compress(Bitmap.CompressFormat.JPEG, 95, cos);
        cos.flush();
        Log.d("Bitmap saved, size = " + (cos.getBytesWritten() / 1024) + "k");
        smaller.recycle();
        System.gc();
    } catch (FileNotFoundException e) {
        Log.e("File not found while storing image.", e);
        return false;
    } catch (Exception e) {
        Log.a("Error storing image.", e);
        return false;
    } finally {
        Util.ensureClosed(is);
        Util.ensureClosed(cos);
    }

    // Create a StoredFile database entry for this locally saved file.
    StoredFile storedFile = new StoredFile();
    storedFile.setId(getStoredFileId());
    storedFile.setOriginalUri(uri.toString());
    storedFile.setLocalFilePath(localFile.getPath());
    storedFile.setMimeType("image/jpeg");
    FileStore db = ApptentiveDatabase.getInstance(context);
    return db.putStoredFile(storedFile);
}

From source file:joshuatee.wx.UtilityFTP.java

public static String[] GetNidsArr(Context c, String url, String path, String frame_cnt_str) {

    int frame_cnt = Integer.parseInt(frame_cnt_str);
    String[] nids_arr = new String[frame_cnt];

    try {/* w  ww .jav a 2 s.  c  om*/
        FTPClient ftp = new FTPClient();

        //String user = "ftp";
        //String pass = "anonymous";

        ftp.connect(url);

        if (!ftp.login("ftp", "anonymous")) {
            ftp.logout();
        }

        ftp.setFileType(FTP.BINARY_FILE_TYPE);
        int reply = ftp.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
        }

        ftp.enterLocalPassiveMode();
        ftp.changeWorkingDirectory(path);
        //reply = ftp.getReplyCode();

        FTPFile[] ftpFiles = ftp.listFiles();

        //get newest .xml file name from ftp server
        java.util.Date lastMod = ftpFiles[0].getTimestamp().getTime();
        FTPFile choice = ftpFiles[0];

        for (FTPFile file : ftpFiles) {
            if (file.getTimestamp().getTime().after(lastMod) && !file.getName().equals("sn.last")) {
                choice = file;
                lastMod = file.getTimestamp().getTime();
            }
        }

        int seq = Integer.parseInt(choice.getName().replace("sn.", "")); // was ALl
        int j = 0;
        int k = seq - frame_cnt + 1;
        for (j = 0; j < frame_cnt; j++) {
            // files range from 0000 to 0250, if num is negative add 251
            int tmp_k = k;

            if (tmp_k < 0)
                tmp_k = tmp_k + 251;

            nids_arr[j] = "sn." + String.format("%4s", Integer.toString(tmp_k)).replace(' ', '0');
            k++;
        }

        FileOutputStream fos;
        for (j = 0; j < frame_cnt; j++) {
            fos = c.openFileOutput(nids_arr[j], Context.MODE_PRIVATE);
            ftp.retrieveFile(nids_arr[j], fos);
            fos.close();
        }

        ftp.logout();
        ftp.disconnect();

    } catch (Exception ex) {
        ex.printStackTrace();
    }

    return nids_arr;

}

From source file:tr.com.turkcellteknoloji.turkcellupdater.UpdateManager.java

private void installPackage(final Context context, final byte[] apkContents, final UpdateListener listener) {
    final AsyncTask<Void, Void, File> task = new AsyncTask<Void, Void, File>() {
        volatile Exception exception;

        @SuppressLint("WorldReadableFiles")
        @Override//from  w  w w.  j  av a  2 s. c  om
        protected File doInBackground(Void... params) {
            try {
                if (Utilities.isNullOrEmpty(apkContents)) {
                    throw new NullPointerException("apkContents");
                }

                String tempFileName = "nextversion.apk";
                File tempFile = context.getFileStreamPath(tempFileName);
                if (tempFile.exists()) {
                    tempFile.delete();
                }

                FileOutputStream fout = context.openFileOutput(tempFileName, Context.MODE_WORLD_READABLE);
                try {
                    fout.write(apkContents);
                    fout.flush();
                } finally {
                    try {
                        fout.close();
                    } catch (Exception e) {
                        // omit
                    }
                }

                return tempFile;

            } catch (Exception e) {
                exception = e;
                Log.e("Couldn't save apk", e);
                return null;
            }
        }

        @Override
        protected void onPostExecute(File result) {
            if (exception == null) {
                try {
                    Uri data = Uri.fromFile(result);
                    String type = "application/vnd.android.package-archive";
                    Intent promptInstall = new Intent(Intent.ACTION_VIEW);
                    promptInstall.setDataAndType(data, type);
                    context.startActivity(promptInstall);
                    if (listener != null) {
                        listener.onUpdateCompleted();
                    }
                    return;
                } catch (Exception e) {
                    exception = e;
                }
            }

            if (listener == null) {
                Log.e("Update failed", exception);
            } else {
                listener.onUpdateFailed(exception);
            }

        }

    };
    task.execute();
}

From source file:com.polyvi.xface.extension.camera.XCameraExt.java

private File createCaptureFile(int encodingType) {
    Context context = getContext();
    String picName = "";
    File photo = null;/*from   w  w  w  .j a  v  a 2 s . c  o m*/
    long time = Calendar.getInstance().getTimeInMillis();
    if (mEncodingType == JPEG) {
        picName = String.valueOf(time) + ".jpg";
    } else if (mEncodingType == PNG) {
        picName = String.valueOf(time) + ".png";
    } else {
        throw new IllegalArgumentException("Invalid Encoding Type: " + mEncodingType);
    }

    photo = context.getFileStreamPath(picName);
    if (!photo.exists()) {
        try {
            FileOutputStream outStream = context.openFileOutput(picName,
                    Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);
            outStream.close();
            photo = context.getFileStreamPath(picName);
        } catch (FileNotFoundException e) {
            XLog.e(CLASS_NAME, "Create picture failed!");
        } catch (IOException e) {
            XLog.e(CLASS_NAME, "Close picture fileStream failed!");
        }
    }
    return photo;
}

From source file:research.sg.edu.edapp.kb.KbSoftKeyboard.java

private void writeToFile(String data, Context context) {
    try {//  w  w w.j  a  v  a  2  s. c o  m
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(
                context.openFileOutput("config.txt", Context.MODE_PRIVATE));
        outputStreamWriter.write(data);
        outputStreamWriter.close();
    } catch (IOException e) {
        Log.e("Exception", "File write failed: " + e.toString());
    }
}

From source file:com.entertailion.android.slideshow.utils.Utils.java

/**
 * Get string version of HTML for a web page. Cache HTML for future acccess.
 * /*from w ww  . j a  v a2 s  .  c o m*/
 * @param context
 * @param url
 * @param refresh
 * @return
 */
public synchronized static final String getCachedData(Context context, String url, boolean refresh) {
    Log.d(LOG_TAG, "getCachedData: " + url);
    String data = null;
    boolean exists = false;
    String cleanUrl = "cache." + clean(url);
    File file = context.getFileStreamPath(cleanUrl);
    if (file != null && file.exists()) {
        exists = true;
    }

    if (!refresh && exists) {
        try {
            FileInputStream fis = context.openFileInput(cleanUrl);
            BufferedReader br = new BufferedReader(new InputStreamReader(fis));
            StringBuffer buffer = new StringBuffer();
            for (String line; (line = br.readLine()) != null;) {
                buffer.append(line);
            }
            fis.close();
            data = buffer.toString();
        } catch (Exception e) {
            Log.e(LOG_TAG, "Error getData: " + url, e);
        }
    } else {
        boolean found = false;
        StringBuilder builder = new StringBuilder();
        try {
            InputStream stream = new HttpRequestHelper().getHttpStream(url);
            BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
            stream.close();
            found = true;
        } catch (IOException e) {
            Log.e(LOG_TAG, "Error getData: " + url, e);
        } catch (Exception e) {
            Log.e(LOG_TAG, "stream is NULL");
        }
        data = builder.toString();
        if (!found && exists) {
            try {
                FileInputStream fis = context.openFileInput(cleanUrl);
                BufferedReader br = new BufferedReader(new InputStreamReader(fis));
                StringBuffer buffer = new StringBuffer();
                for (String line; (line = br.readLine()) != null;) {
                    buffer.append(line);
                }
                fis.close();
                data = buffer.toString();
            } catch (Exception e) {
                Log.e(LOG_TAG, "Error getData: " + url, e);
            }
        }
        if (data != null && data.trim().length() > 0) {
            try {
                FileOutputStream fos = context.openFileOutput(cleanUrl, Context.MODE_PRIVATE);
                fos.write(data.getBytes());
                fos.close();
            } catch (FileNotFoundException e) {
                Log.e(LOG_TAG, "Error getData: " + url, e);
            } catch (IOException e) {
                Log.e(LOG_TAG, "Error getData: " + url, e);
            }
        }
    }
    return data;
}

From source file:com.mhise.util.MHISEUtil.java

/**
*  Returns a list of the file path containing file with extensions .p12 , .pfx , .p7b 
*
*//*from   w  w  w .  j  av  a 2  s .  com*/
public static void movePKCS12(String path, Context ctx) {

    //Move PFX or p12 store to Mobius store 
    /*  try {   
    File certificateFile=new File(path);            
    File _mobiusDirectory = new File(Constants.defaultP12StorePath);            
    if(!_mobiusDirectory.exists())
    {
          _mobiusDirectory.mkdir();
    }            
    File newKeystoreFile = new File(Constants.defaultP12StorePath + Constants.defaultP12StoreName);            
    FileInputStream fin= new FileInputStream(certificateFile);
    FileOutputStream fout= new FileOutputStream(newKeystoreFile);            
    byte buffer[] = new byte[(int) certificateFile.length()];            
    fin.read(buffer);            
    fout.write(buffer);            
    movedPath = newKeystoreFile.getAbsolutePath();
            
                    
        } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        }
      */

    try {
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        //Get saved password
        SharedPreferences sharedPreferences = ctx.getSharedPreferences(Constants.PREFS_NAME,
                Context.MODE_PRIVATE);
        String strPassword = sharedPreferences.getString(Constants.KEY_PKCS12_PASSWORD, null);
        char[] password = strPassword.toCharArray();

        //Load Selected keystore
        File input = new File(path);
        FileInputStream fin = new FileInputStream(input);
        keyStore.load(fin, password);

        OutputStream fos = ctx.openFileOutput(Constants.defaultP12StoreName, Context.MODE_PRIVATE);
        keyStore.store(fos, password);
        fos.close();

    } catch (KeyStoreException e) {
        // TODO: handle exception
        Logger.debug("MHISEUtil-->makePKCS12Store", "KeyStoreException: " + e);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        Logger.debug("MHISEUtil-->makePKCS12Store", "FileNotFoundException: " + e);
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        Logger.debug("MHISEUtil-->makePKCS12Store", "NoSuchAlgorithmException: " + e);
        e.printStackTrace();
    } catch (CertificateException e) {
        // TODO Auto-generated catch block
        Logger.debug("MHISEUtil-->makePKCS12Store", "CertificateException: " + e);
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        Logger.debug("MHISEUtil-->makePKCS12Store", "IOException: " + e);
        e.printStackTrace();
    }

}