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:com.github.javiersantos.piracychecker.LibraryUtils.java

@SuppressLint("SdCardPath")
static PirateApp getPirateApp(Context context, boolean lpf, boolean stores) {
    if (!lpf && !stores)
        return null;
    for (PirateApp app : getApps()) {
        if ((lpf && app.isUnauthorized()) || (stores && !app.isUnauthorized())) {
            StringBuilder builder = new StringBuilder();
            for (String s : app.getPack()) {
                builder.append(s);/*  www . j a  v a  2s .c  o m*/
            }
            String pack = builder.toString();
            PackageManager pm = context.getPackageManager();
            try {
                PackageInfo info = pm.getPackageInfo(pack, PackageManager.GET_META_DATA);
                if (info != null)
                    return app;
            } catch (PackageManager.NameNotFoundException ignored1) {
                try {
                    Intent intent = pm.getLaunchIntentForPackage(pack);
                    if (isIntentAvailable(context, intent)) {
                        return app;
                    }
                } catch (Exception ignored2) {
                    try {
                        if (hasPermissions(context)) {
                            File file1 = new File("/data/app/" + pack + "-1/base.apk");
                            File file2 = new File("/data/app/" + pack + "-2/base.apk");
                            File file3 = new File("/data/app/" + pack + ".apk");
                            File file4 = new File("/data/data/" + pack + ".apk");
                            File file5 = new File("/data/data/" + pack);
                            File file6 = new File(context.getFilesDir().getPath() + pack + ".apk");
                            File file7 = new File(context.getFilesDir().getPath() + pack);
                            File file8 = new File(
                                    Environment.getExternalStorageDirectory() + "/Android/data/" + pack);
                            if (file1.exists() || file2.exists() || file3.exists() || file4.exists()
                                    || file5.exists() || file6.exists() || file7.exists() || file8.exists()) {
                                return app;
                            }
                        }
                    } catch (Exception ignored) {
                    }
                }
            }
        }
    }
    return null;
}

From source file:com.sentaroh.android.SMBSync2.GlobalParameters.java

@SuppressLint("NewApi")
public void initCommon(Context c) {

    if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        externalStorageIsMounted = false;
    } else {//from   w  ww  .j  a  v  a2  s. c  om
        externalStorageIsMounted = true;
    }

    if (Build.VERSION.SDK_INT >= 23) {
        externalStorageAccessIsPermitted = (c.checkSelfPermission(
                Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED);
    } else {
        externalStorageAccessIsPermitted = true;
    }

    internalRootDirectory = Environment.getExternalStorageDirectory().toString();
    usbRootDirectory = LocalMountPoint.getUsbStorageDir();
    sdcardRootDirectory = SafUtil.getSafExternalSdcardDir(c);
    applicationRootDirectory = c.getFilesDir().toString();
}

From source file:com.google.android.apps.muzei.provider.MuzeiProvider.java

private File getCacheFileForArtworkUri(Uri artworkUri) {
    Context context = getContext();
    if (context == null || artworkUri == null) {
        return null;
    }// w  w  w. j a va2  s .  co  m
    File directory = new File(context.getFilesDir(), "artwork");
    if (!directory.exists() && !directory.mkdirs()) {
        return null;
    }
    String[] projection = { BaseColumns._ID, MuzeiContract.Artwork.COLUMN_NAME_IMAGE_URI,
            MuzeiContract.Artwork.COLUMN_NAME_TOKEN };
    Cursor data = queryArtwork(artworkUri, projection, null, null, null);
    if (data == null) {
        return null;
    }
    if (!data.moveToFirst()) {
        Log.e(TAG, "Invalid artwork URI " + artworkUri);
        return null;
    }
    // While normally we'd use data.getLong(), we later need this as a String so the automatic conversion helps here
    String id = data.getString(0);
    String imageUri = data.getString(1);
    String token = data.getString(2);
    data.close();
    if (TextUtils.isEmpty(imageUri) && TextUtils.isEmpty(token)) {
        return new File(directory, id);
    }
    // Otherwise, create a unique filename based on the imageUri and token
    StringBuilder filename = new StringBuilder();
    if (!TextUtils.isEmpty(imageUri)) {
        Uri uri = Uri.parse(imageUri);
        filename.append(uri.getScheme()).append("_").append(uri.getHost()).append("_");
        String encodedPath = uri.getEncodedPath();
        if (!TextUtils.isEmpty(encodedPath)) {
            int length = encodedPath.length();
            if (length > 60) {
                encodedPath = encodedPath.substring(length - 60);
            }
            encodedPath = encodedPath.replace('/', '_');
            filename.append(encodedPath).append("_");
        }
    }
    // Use the imageUri if available, otherwise use the token
    String unique = !TextUtils.isEmpty(imageUri) ? imageUri : token;
    try {
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(unique.getBytes("UTF-8"));
        byte[] digest = md.digest();
        for (byte b : digest) {
            if ((0xff & b) < 0x10) {
                filename.append("0").append(Integer.toHexString((0xFF & b)));
            } else {
                filename.append(Integer.toHexString(0xFF & b));
            }
        }
    } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
        filename.append(unique.hashCode());
    }
    return new File(directory, filename.toString());
}

From source file:com.webkey.Ipc.java

public Ipc(Context context) {
    _context = context;/*from  ww  w  . j ava 2s.  c  o  m*/
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    port = prefs.getString("port", "80");
    sslport = prefs.getString("sslport", "443");

    random = prefs.getString("random", "");
    if (random.length() == 0) {
        Random rnd = new Random();
        for (int i = 0; i < 16; i++) {
            int c = rnd.nextInt(62);
            if (c < 10)
                random += (char) (c + 48);
            else if (c < 36)
                random += (char) (c + 65 - 10);
            else
                random += (char) (c + 97 - 36);
        }
        SharedPreferences.Editor ed = prefs.edit();
        ed.putString("random", random);
        ed.commit();
    }
    workDir = context.getFilesDir().getPath() + "/";
    readAuthKey();
}

From source file:com.raspi.chatapp.ui.chatting.SendImageFragment.java

/**
 * saves a copy in the internal storage. This may be used for displaying when
 * rendering the real image in background. As this is image is really low
 * quality it is loaded instantly (size is a couple bytes) you can load
 * this in the main thread while the background thread will do the heavy
 * loading task./* www .  j a  v  a2  s  . c o m*/
 *
 * @param context      the context used to get the localStorage
 * @param fileLocation the location of the file that is to be saved
 * @param id           the messageId of the imageMessage, for the file name
 * @param chatId       the chatId of the chat the image is from, for the file name
 */
private void saveImageCopy(Context context, String fileLocation, Long id, String chatId) {
    try {
        //old images bitmap
        Bitmap oldImg = BitmapFactory.decodeFile(fileLocation);
        // sample the height to 50 and maintain the aspect ratio
        float height = 50;
        float x = oldImg.getHeight() / height;
        float width = oldImg.getWidth() / x;

        // generate the destination file
        File destFile = new File(context.getFilesDir(), chatId + "-" + id + ".jpg");
        OutputStream out = new FileOutputStream(destFile);
        // generate the bitmap to compress to file
        Bitmap image = Bitmap.createScaledBitmap(oldImg, (int) width, (int) height, true);
        // compress the bitmap to file
        image.compress(Bitmap.CompressFormat.JPEG, 20, out);
        out.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.colorchen.qbase.utils.FileUtil.java

/**
 * /*from   ww  w . j  a  v a2  s .c  o  m*/
 * <p>/data/data/com.xxx.xxx/files</p>
 *
 * @return {@code true}: ?<br>{@code false}: 
 */
public static boolean cleanInternalFiles(Context context) {
    return FileUtil.deleteFilesInDir(context.getFilesDir());
}

From source file:com.colorchen.qbase.utils.FileUtil.java

/**
 * ?/*www . j av a  2s . com*/
 * <p>/data/data/com.xxx.xxx/databases</p>
 *
 * @return {@code true}: ?<br>{@code false}: 
 */
public static boolean cleanInternalDbs(Context context) {
    return FileUtil.deleteFilesInDir(context.getFilesDir().getParent() + File.separator + "databases");
}

From source file:com.colorchen.qbase.utils.FileUtil.java

/**
 * SP/*from ww w  .  jav a2 s  . c  o  m*/
 * <p>/data/data/com.xxx.xxx/shared_prefs</p>
 *
 * @return {@code true}: ?<br>{@code false}: 
 */
public static boolean cleanInternalSP(Context context) {
    return FileUtil.deleteFilesInDir(context.getFilesDir().getParent() + File.separator + "shared_prefs");
}

From source file:com.mitre.holdshort.AlertLogger.java

public AlertLogger(String airport, Context ctx) {

    this.ctx = ctx;
    this.airport = airport;
    try {//from w  ww .j  av a 2  s  .c  o m

        alertFTPClient = new FTPClient();
        alertFTPClient.connect(ftpHost, 21);
        alertFTPClient.login(ftpUser, ftpPassword);
        alertFTPClient.enterLocalPassiveMode();

    } catch (SocketException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (UnknownHostException e) {
        System.err.println("No Connection For FTP Client");
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // Check for or create old alert file for when FTPClient cannot connect
    File oldAlerts = new File(ctx.getFilesDir() + "/oldAlerts.dat");
    if (!(oldAlerts.exists())) {
        try {
            oldAlerts.createNewFile();
        } catch (IOException e1) {

        }
    } else {
        //Old Alert file exists & push old alerts to the ftp server
        logOldAlerts();
    }

}

From source file:com.remobile.file.FileUtils.java

protected HashMap<String, String> getAvailableFileSystems(Activity activity) {
    Context context = activity.getApplicationContext();
    HashMap<String, String> availableFileSystems = new HashMap<String, String>();

    availableFileSystems.put("files", context.getFilesDir().getAbsolutePath());
    availableFileSystems.put("documents", new File(context.getFilesDir(), "Documents").getAbsolutePath());
    availableFileSystems.put("cache", context.getCacheDir().getAbsolutePath());
    availableFileSystems.put("root", "/");
    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        try {/*from   ww  w .  j  a  v  a  2 s . c  om*/
            availableFileSystems.put("files-external", context.getExternalFilesDir(null).getAbsolutePath());
            availableFileSystems.put("sdcard", Environment.getExternalStorageDirectory().getAbsolutePath());
            availableFileSystems.put("cache-external", context.getExternalCacheDir().getAbsolutePath());
        } catch (NullPointerException e) {
            Log.d(LOG_TAG, "External storage unavailable, check to see if USB Mass Storage Mode is on");
        }
    }

    return availableFileSystems;
}