Example usage for android.content Context getFilesDir

List of usage examples for android.content Context getFilesDir

Introduction

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

Prototype

public abstract File getFilesDir();

Source Link

Document

Returns the absolute path to the directory on the filesystem where files created with #openFileOutput are stored.

Usage

From source file:org.fdroid.fdroid.installer.ApkCache.java

/**
 * Copy the APK to the safe location inside of the protected area
 * of the app to prevent attacks based on other apps swapping the file
 * out during the install process. Most likely, apkFile was just downloaded,
 * so it should still be in the RAM disk cache.
 *//*from   w w w. ja v a  2  s.co m*/
public static SanitizedFile copyApkFromCacheToFiles(Context context, File apkFile, Apk expectedApk)
        throws IOException {
    SanitizedFile sanitizedApkFile = null;

    try {
        sanitizedApkFile = SanitizedFile
                .knownSanitized(File.createTempFile("install-", ".apk", context.getFilesDir()));
        FileUtils.copyFile(apkFile, sanitizedApkFile);

        // verify copied file's hash with expected hash from Apk class
        if (!verifyApkFile(sanitizedApkFile, expectedApk.hash, expectedApk.hashType)) {
            FileUtils.deleteQuietly(apkFile);
            throw new IOException(apkFile + " failed to verify!");
        }

        return sanitizedApkFile;
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    } finally {
        // 20 minutes the start of the install process, delete the file
        final File apkToDelete = sanitizedApkFile;
        new Thread() {
            @Override
            public void run() {
                android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_LOWEST);
                try {
                    Thread.sleep(1200000);
                } catch (InterruptedException ignored) {
                } finally {
                    FileUtils.deleteQuietly(apkToDelete);
                }
            }
        }.start();
    }
}

From source file:Main.java

public static File getNewFile(Context context, String folderName) {

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.CHINA);

    String timeStamp = simpleDateFormat.format(new Date());

    String path;/*from  w  w  w  . ja  v  a2 s  .co m*/
    if (isSDAvailable()) {
        path = getFolderName(folderName) + File.separator + timeStamp + ".jpg";
    } else {
        path = context.getFilesDir().getPath() + File.separator + timeStamp + ".jpg";
    }

    if (TextUtils.isEmpty(path)) {
        return null;
    }

    return new File(path);
}

From source file:org.metasyntactic.utilities.ExceptionUtilities.java

public static void registerExceptionHandler(Context context) {
    PackageManager pm = context.getPackageManager();
    try {/*  ww  w . j  av a 2s  . c  o  m*/
        PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
        Version = pi.versionName;
        Package = pi.packageName;
        FilesPath = context.getFilesDir().getAbsolutePath();
    } catch (NameNotFoundException e) {
        e.printStackTrace();
    }

    new Thread() {
        @Override
        public void run() {
            submitStackTraces();
            Thread.setDefaultUncaughtExceptionHandler(DEFAULT_EXCEPTION_HANDLER);
        }
    }.start();
}

From source file:Main.java

/**
 * Show a level/*from   w  w  w .  j a  v  a  2s  .  c om*/
 * 
 * @param context The context
 * @param level The level
 */
public static void showLevel(Context context, int level) {
    String filename;
    switch (level) {
    case 1: {
        filename = "ground_floor.png";
        break;
    }
    case 2: {
        filename = "talks_floor.png";
        break;
    }

    default: {
        return;
    }
    }
    File f = new File(context.getFilesDir() + "/" + filename);
    try {
        if (f.exists() == false) {
            InputStream is = context.getAssets().open(filename);
            FileOutputStream fos = context.openFileOutput(filename, Context.MODE_WORLD_READABLE);
            byte[] buffer = new byte[is.available()];
            is.read(buffer);
            // write the stream to file
            fos.write(buffer, 0, buffer.length);
            fos.close();
            is.close();
        }

        // Prepare the intent
        //TODO - create an activity for this instead. Internal viewers might be quite heavy
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(f), "image/png");
        context.startActivity(intent);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:Main.java

/**
 * Returns the local store of reliable server certificates, explicitly accepted by the user.
 * //  w  w w  .  j  a va2 s  .c  o  m
 * Returns a KeyStore instance with empty content if the local store was never created.
 * 
 * Loads the store from the storage environment if needed.
 * 
 * @param context                       Android context where the operation is being performed.
 * @return                              KeyStore instance with explicitly-accepted server certificates. 
 * @throws KeyStoreException            When the KeyStore instance could not be created.
 * @throws IOException                  When an existing local trust store could not be loaded.
 * @throws NoSuchAlgorithmException     When the existing local trust store was saved with an unsupported algorithm.
 * @throws CertificateException         When an exception occurred while loading the certificates from the local trust store.
 */
private static KeyStore getKnownServersStore(Context context)
        throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException {
    if (mKnownServersStore == null) {
        //mKnownServersStore = KeyStore.getInstance("BKS");
        mKnownServersStore = KeyStore.getInstance(KeyStore.getDefaultType());
        File localTrustStoreFile = new File(context.getFilesDir(), LOCAL_TRUSTSTORE_FILENAME);
        Log.d(TAG, "Searching known-servers store at " + localTrustStoreFile.getAbsolutePath());
        if (localTrustStoreFile.exists()) {
            InputStream in = new FileInputStream(localTrustStoreFile);
            try {
                mKnownServersStore.load(in, LOCAL_TRUSTSTORE_PASSWORD.toCharArray());
            } finally {
                in.close();
            }
        } else {
            mKnownServersStore.load(null, LOCAL_TRUSTSTORE_PASSWORD.toCharArray()); // necessary to initialize an empty KeyStore instance
        }
    }
    return mKnownServersStore;
}

From source file:Main.java

public static boolean writeToFile(Context ctx, String strContent, String filename) {
    boolean bReturn = true;
    FileOutputStream osw = null;/* ww  w  .  j  a  v  a2 s .  com*/

    try {
        //Make sub directories if needed
        String[] split = filename.split(File.separator);
        String file = split[split.length - 1];
        String path = filename.substring(0, filename.indexOf(file));
        if (path != "")
            new File(ctx.getFilesDir() + File.separator + path).mkdirs();
        File outputFile = new File(ctx.getFilesDir() + File.separator + filename);

        osw = new FileOutputStream(outputFile);
        osw.write(strContent.getBytes());
        osw.close();
    } catch (Exception e) {
        e.printStackTrace();
        bReturn = false;
    } finally {
        try {
            if (osw != null)
                osw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    return bReturn;
}

From source file:com.gelakinetic.mtgfam.helpers.ZipUtils.java

/**
 * Zips all files specified in an ArrayList into a given file
 *
 * @param zipFile The file to zip files into
 * @param files   The files to be zipped
 * @param context The application context, for getting files and the like
 * @throws IOException IOException Thrown if something goes wrong with zipping and reading
 *///w w w.  jav  a2 s.  c  o m
private static void zipIt(File zipFile, ArrayList<File> files, Context context) throws IOException {

    byte[] buffer = new byte[1024];

    FileOutputStream fos = new FileOutputStream(zipFile);
    ZipOutputStream zos = new ZipOutputStream(fos);
    assert context.getFilesDir() != null;
    for (File file : files) {
        ZipEntry ze = new ZipEntry(file.getName());
        zos.putNextEntry(ze);

        FileInputStream in = new FileInputStream(file);

        int len;
        while ((len = in.read(buffer)) > 0) {
            zos.write(buffer, 0, len);
        }
        in.close();
    }

    zos.closeEntry();
    zos.close();
}

From source file:com.ruesga.rview.misc.CacheHelper.java

public static File createNewTemporaryFile(Context context, String suffix) throws IOException {
    String ts = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(new Date());
    File storageDir = context.getFilesDir();
    if (storageDir.exists() || storageDir.mkdirs()) {
        File file = new File(storageDir.getAbsolutePath(), ts + suffix);
        if (file.createNewFile()) {
            return new File(storageDir.getAbsolutePath(), ts + suffix);
        }/*from w ww.j a v  a 2 s. c o  m*/
    }
    return null;
}

From source file:com.cyberocw.habittodosecretary.file.StorageHelper.java

public static File getSharedPreferencesFile(Context mContext) {
    File appData = mContext.getFilesDir().getParentFile();
    String packageName = mContext.getApplicationContext().getPackageName();
    return new File(appData + System.getProperty("file.separator") + "shared_prefs"
            + System.getProperty("file.separator") + packageName + "_preferences.xml");
}

From source file:com.cerema.cloud2.lib.common.network.NetworkUtils.java

/**
 * Returns the local store of reliable server certificates, explicitly accepted by the user.
 * //from w  w  w  .java  2  s .c om
 * Returns a KeyStore instance with empty content if the local store was never created.
 * 
 * Loads the store from the storage environment if needed.
 * 
 * @param context                       Android context where the operation is being performed.
 * @return                              KeyStore instance with explicitly-accepted server certificates. 
 * @throws KeyStoreException            When the KeyStore instance could not be created.
 * @throws IOException                  When an existing local trust store could not be loaded.
 * @throws NoSuchAlgorithmException     When the existing local trust store was saved with an unsupported algorithm.
 * @throws CertificateException         When an exception occurred while loading the certificates from the local 
 *                               trust store.
 */
private static KeyStore getKnownServersStore(Context context)
        throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException {
    if (mKnownServersStore == null) {
        //mKnownServersStore = KeyStore.getInstance("BKS");
        mKnownServersStore = KeyStore.getInstance(KeyStore.getDefaultType());
        File localTrustStoreFile = new File(context.getFilesDir(), LOCAL_TRUSTSTORE_FILENAME);
        Log_OC.d(TAG, "Searching known-servers store at " + localTrustStoreFile.getAbsolutePath());
        if (localTrustStoreFile.exists()) {
            InputStream in = new FileInputStream(localTrustStoreFile);
            try {
                mKnownServersStore.load(in, LOCAL_TRUSTSTORE_PASSWORD.toCharArray());
            } finally {
                in.close();
            }
        } else {
            // next is necessary to initialize an empty KeyStore instance
            mKnownServersStore.load(null, LOCAL_TRUSTSTORE_PASSWORD.toCharArray());
        }
    }
    return mKnownServersStore;
}