Example usage for android.content Context getFileStreamPath

List of usage examples for android.content Context getFileStreamPath

Introduction

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

Prototype

public abstract File getFileStreamPath(String name);

Source Link

Document

Returns the absolute path on the filesystem where a file created with #openFileOutput is stored.

Usage

From source file:org.matrix.matrixandroidsdk.db.ConsoleMediasCache.java

/**
 * Save a media to the local cache// w w w  . j a  v  a2 s .  c  o m
 * it could be used for unsent media to allow them to be resent.
 * @param stream the file stream to save
 * @param defaultFileName the filename is provided, if null, a filename will be generated
 * @return the media cache URL
 */
public static String saveMedia(InputStream stream, Context context, String defaultFileName) {
    String filename = (defaultFileName == null) ? ("file" + System.currentTimeMillis()) : defaultFileName;
    String cacheURL = null;

    try {
        FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE);

        try {
            byte[] buf = new byte[1024 * 32];

            int len;
            while ((len = stream.read(buf)) != -1) {
                fos.write(buf, 0, len);
            }
        } catch (Exception e) {
        }

        fos.flush();
        fos.close();
        stream.close();

        cacheURL = Uri.fromFile(context.getFileStreamPath(filename)).toString();
    } catch (Exception e) {

    }

    return cacheURL;
}

From source file:net.tawacentral.roger.secrets.FileUtils.java

/**
 * Cleanup any residual data files from a previous bad run, if any.  The
 * algorithm is as follows://w ww. j  a  v a2 s .  c o m
 *
 * - delete any file with "new" in the name.  These are possibly partial
 *   writes, so their contents is undefined.
 * - if no secrets file exists, rename the most recent auto restore point
 *   file to secrets.
 * - if too many auto restore point files exist, delete the extra ones.
 *   However, don't delete any auto-backups younger than 48 hours.
 *
 * @param context Activity context in which the save is called.
 */
public static void cleanupDataFiles(Context context) {
    Log.d(LOG_TAG, "FileUtils.cleanupDataFiles");
    synchronized (lock) {
        String[] filenames = context.fileList();
        int oldCount = filenames.length;
        boolean secretsFileExists = context.getFileStreamPath(SECRETS_FILE_NAME).exists();

        // Cleanup any partial saves and find the most recent auto-backup file.
        {
            File mostRecent = null;
            int mostRecentIndex = -1;
            for (int i = 0; i < filenames.length; ++i) {
                String filename = filenames[i];
                if (-1 != filename.indexOf("new")) {
                    context.deleteFile(filename);
                    --oldCount;
                    filenames[i] = null;
                } else if (filename.startsWith(RP_PREFIX)) {
                    if (!secretsFileExists) {
                        File f = context.getFileStreamPath(filename);
                        if (null == mostRecent || f.lastModified() > mostRecent.lastModified()) {
                            mostRecent = f;
                            mostRecentIndex = i;
                        }
                    }
                } else {
                    --oldCount;
                    filenames[i] = null;
                }
            }

            // If we don't have a secrets file but found an auto-backup file,
            // rename the more recent auto-backup to secrets.
            if (null != mostRecent) {
                mostRecent.renameTo(context.getFileStreamPath(SECRETS_FILE_NAME));
                --oldCount;
                filenames[mostRecentIndex] = null;
            }
        }

        // If there are too many old files, delete the oldest extra ones.
        while (oldCount > 10) {
            File oldest = null;
            int oldestIndex = -1;

            for (int i = 0; i < filenames.length; ++i) {
                String filename = filenames[i];
                if (null == filename)
                    continue;

                File f = context.getFileStreamPath(filename);
                if (null == oldest || f.lastModified() < oldest.lastModified()) {
                    oldest = f;
                    oldestIndex = i;
                }
            }

            if (null != oldest) {
                // If the oldest file is not too old, then just break out of the
                // loop.  We don't want to delete any "old" files that are too
                // recent.
                if (!FileUtils.isRestorePointTooOld(oldest))
                    break;

                oldest.delete();
                --oldCount;
                filenames[oldestIndex] = null;
            }
        }
    }
}

From source file:edu.cmu.cs.diamond.android.Filter.java

public Filter(int resourceId, Context context, String name, String[] args, byte[] blob) throws IOException {
    Resources r = context.getResources();
    String resourceName = r.getResourceEntryName(resourceId);
    File f = context.getFileStreamPath(resourceName);

    if (!f.exists()) {
        InputStream ins = r.openRawResource(resourceId);
        byte[] buf = IOUtils.toByteArray(ins);
        FileOutputStream fos = context.openFileOutput(resourceName, Context.MODE_PRIVATE);
        IOUtils.write(buf, fos);/*from  w w  w. ja  v  a2 s .  c  o m*/
        context.getFileStreamPath(resourceName).setExecutable(true);
        fos.close();
    }

    ProcessBuilder pb = new ProcessBuilder(f.getAbsolutePath());
    Map<String, String> env = pb.environment();
    tempDir = File.createTempFile("filter", null, context.getCacheDir());
    tempDir.delete(); // Delete file and create directory.
    if (!tempDir.mkdir()) {
        throw new IOException("Unable to create temporary directory.");
    }
    env.put("TEMP", tempDir.getAbsolutePath());
    env.put("TMPDIR", tempDir.getAbsolutePath());
    proc = pb.start();
    is = proc.getInputStream();
    os = proc.getOutputStream();

    sendInt(1);
    sendString(name);
    sendStringArray(args);
    sendBinary(blob);

    while (this.getNextToken().tag != TagEnum.INIT)
        ;
    Log.d(TAG, "Filter initialized.");
}

From source file:com.daskiworks.ghwatch.backend.UnreadNotificationsService.java

/**
 * Create service.//from  w w  w  . ja v a2  s .c o m
 * 
 * @param context this service runs in
 */
public UnreadNotificationsService(Context context) {
    this.context = context;
    persistFile = context.getFileStreamPath(persistFileName);
    this.authenticationManager = AuthenticationManager.getInstance();
}

From source file:com.youTransactor.uCube.mdm.MDMManager.java

public void initialize(Context context) {
    SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);

    onSharedPreferenceChanged(settings, null);

    settings.registerOnSharedPreferenceChangeListener(this);

    try {//from w  w w .  ja v a  2s  .c o m
        KeyStore keystoreCA = KeyStore.getInstance(KEYSTORE_TYPE);
        keystoreCA.load(context.getResources().openRawResource(R.raw.keystore), PWD);

        KeyStore keystoreClient = null;

        File file = context.getFileStreamPath(KEYSTORE_CLIENT_FILENAME);

        if (file.exists()) {
            keystoreClient = KeyStore.getInstance(KEYSTORE_TYPE);
            InputStream in = new FileInputStream(file);
            keystoreClient.load(in, PWD);
        }

        ready = keystoreClient != null && keystoreClient.getKey(MDM_CLIENT_CERT_ALIAS, PWD) != null;

        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(keystoreCA);

        KeyManagerFactory kmf = KeyManagerFactory.getInstance("X509");
        kmf.init(keystoreClient, PWD);

        sslContext = SSLContext.getInstance("TLS");

        sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

    } catch (Exception e) {
        LogManager.debug(MDMManager.class.getSimpleName(), "load keystore error", e);
    }
}

From source file:edu.mit.mobile.android.imagecache.test.ImageCacheJunitTest.java

/**
 * Loads a file from the assets and saves it to a public location.
 *
 * @return//from  w ww  .jav a2  s.  c  om
 * @throws IOException
 */
private Uri loadLocalFile() throws IOException {

    final String testfile = "logo_locast.png";
    final Context contextInst = getInstrumentation().getContext();
    final Context context = getInstrumentation().getTargetContext();
    final InputStream is = contextInst.getAssets().open(testfile);

    assertNotNull(is);

    final FileOutputStream fos = context.openFileOutput(testfile, Context.MODE_PRIVATE);

    assertNotNull(fos);

    int read = 0;
    final byte[] bytes = new byte[1024];

    while ((read = is.read(bytes)) != -1) {
        fos.write(bytes, 0, read);
    }

    is.close();
    fos.close();

    final File outFile = context.getFileStreamPath(testfile);

    final Uri fileUri = Uri.fromFile(outFile);

    assertNotNull(fileUri);
    return fileUri;
}

From source file:net.wequick.small.ApkBundleLauncher.java

@Override
public File getExtractPath(Bundle bundle) {
    Context context = Small.getContext();
    File packagePath = context.getFileStreamPath(FD_STORAGE);
    return new File(packagePath, bundle.getPackageName());
}

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 .ja va2 s .co  m*/
        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 ww .  j  av a  2s  . 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:com.android.exchange.SyncManager.java

static private String getDeviceIdInternal(Context context) throws IOException {
    if (INSTANCE == null && context == null) {
        throw new IOException("No context for getDeviceId");
    } else if (context == null) {
        context = INSTANCE;/*  w  ww .j a  v  a2  s  .c  o  m*/
    }

    try {
        File f = context.getFileStreamPath("deviceName");
        BufferedReader rdr = null;
        String id;
        if (f.exists() && f.canRead()) {
            rdr = new BufferedReader(new FileReader(f), 128);
            id = rdr.readLine();
            rdr.close();
            return id;
        } else if (f.createNewFile()) {
            BufferedWriter w = new BufferedWriter(new FileWriter(f), 128);
            final String consistentDeviceId = Utility.getConsistentDeviceId(context);
            if (consistentDeviceId != null) {
                // Use different prefix from random IDs.
                id = "androidc" + consistentDeviceId;
            } else {
                id = "android" + System.currentTimeMillis();
            }
            w.write(id);
            w.close();
            return id;
        }
    } catch (IOException e) {
    }
    throw new IOException("Can't get device name");
}