Example usage for android.content Context deleteFile

List of usage examples for android.content Context deleteFile

Introduction

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

Prototype

public abstract boolean deleteFile(String name);

Source Link

Document

Delete the given private file associated with this Context's application package.

Usage

From source file:es.deustotech.piramide.utils.tts.TextToSpeechWeb.java

private static synchronized void speech(final Context context, final String text, final String language) {
    executor.submit(new Runnable() {
        @Override/*w  w w.j  av a2  s  .  com*/
        public void run() {
            try {
                final String encodedUrl = Constants.URL + language + "&q="
                        + URLEncoder.encode(text, Encoding.UTF_8.name());
                final DefaultHttpClient client = new DefaultHttpClient();
                HttpParams params = new BasicHttpParams();
                params.setParameter("http.protocol.content-charset", "UTF-8");
                client.setParams(params);
                final FileOutputStream fos = context.openFileOutput(Constants.MP3_FILE,
                        Context.MODE_WORLD_READABLE);
                try {
                    try {
                        final HttpResponse response = client.execute(new HttpGet(encodedUrl));
                        downloadFile(response, fos);
                    } finally {
                        fos.close();
                    }
                    final String filePath = context.getFilesDir().getAbsolutePath() + "/" + Constants.MP3_FILE;
                    final MediaPlayer player = MediaPlayer.create(context.getApplicationContext(),
                            Uri.fromFile(new File(filePath)));
                    player.start();
                    Thread.sleep(player.getDuration());
                    while (player.isPlaying()) {
                        Thread.sleep(100);
                    }
                    player.stop();

                } finally {
                    context.deleteFile(Constants.MP3_FILE);
                }
            } catch (InterruptedException ie) {
                // ok
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

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  av  a  2 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:com.psiphon3.psiphonlibrary.TunnelManager.java

public static String getServerEntries(Context context) {
    StringBuilder list = new StringBuilder();

    for (String encodedServerEntry : EmbeddedValues.EMBEDDED_SERVER_LIST) {
        list.append(encodedServerEntry);
        list.append("\n");
    }//  w  w w . j a  va2 s .c  o m

    // Import legacy server entries
    try {
        FileInputStream file = context.openFileInput(LEGACY_SERVER_ENTRY_FILENAME);
        BufferedReader reader = new BufferedReader(new InputStreamReader(file));
        StringBuilder json = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            json.append(line);
        }
        file.close();
        JSONObject obj = new JSONObject(json.toString());
        JSONArray jsonServerEntries = obj.getJSONArray("serverEntries");

        // MAX_LEGACY_SERVER_ENTRIES ensures the list we pass through to tunnel-core
        // is unlikely to trigger an OutOfMemoryError
        for (int i = 0; i < jsonServerEntries.length() && i < MAX_LEGACY_SERVER_ENTRIES; i++) {
            list.append(jsonServerEntries.getString(i));
            list.append("\n");
        }

        // Don't need to repeat the import again
        context.deleteFile(LEGACY_SERVER_ENTRY_FILENAME);
    } catch (FileNotFoundException e) {
        // pass
    } catch (IOException | JSONException | OutOfMemoryError e) {
        MyLog.g("prepareServerEntries failed: %s", e.getMessage());
    }

    return list.toString();
}

From source file:es.javocsoft.android.lib.toolbox.ToolBox.java

/**
 * Deletes a file from the application internal storage private folder.
 * //from ww w.j a  v  a2  s .c o  m
 * @param context
 * @param fileName
 * @throws Exception
 */
public static void storage_deleteDataFromInternalStorage(Context context, String fileName) throws Exception {

    try {
        context.deleteFile(fileName);
    } catch (Exception e) {
        throw new Exception("Error deleting data '" + fileName + "' (internal storage) : " + e.getMessage(), e);
    }
}

From source file:org.openintents.safe.CryptoHelper.java

/**
 * Dencrypt a file previously encrypted with
 * encryptFileWithSessionKey().//from  w ww  . j  a va2s .  c om
 * <p/>
 * The original file is not modified
 *
 * @param ctx     Context of activity in order to store temp file
 * @param fileUri Uri to either a stream or a file to read from
 * @return If decryption is successful, returns Uri of a content
 * provider to read the plaintext file.  Upon failure,
 * return null.
 * @throws Exception
 * @author Peli
 */
public Uri decryptFileWithSessionKeyThroughContentProvider(Context ctx, Uri fileUri)
        throws CryptoHelperException {
    if (debug) {
        Log.d(TAG, "fileUri=" + fileUri.toString());
    }
    ContentResolver contentResolver = ctx.getContentResolver();

    String sessionFile = "";
    Uri resultUri = null;
    boolean result = false;

    try {
        InputStream is;
        if (fileUri.getScheme().equals("file")) {
            is = new java.io.FileInputStream(fileUri.getPath());
            if (debug) {
                Log.d(TAG, "Decrypt: Input from " + fileUri.getPath());
            }
        } else {
            is = contentResolver.openInputStream(fileUri);
            if (debug) {
                Log.d(TAG, "Decrypt: Input from " + fileUri.toString());
            }
        }
        FileOutputStream os = null;

        String decryptSession;
        try {
            // create a random session name
            decryptSession = generateSalt();
        } catch (NoSuchAlgorithmException e1) {
            e1.printStackTrace();
            String msg = "Decrypt error: " + e1.getLocalizedMessage();
            throw new CryptoHelperException(msg);
        }
        sessionFile = CryptoContentProvider.SESSION_FILE + "." + decryptSession;
        if (debug) {
            Log.d(TAG, "Decrypt: Output to " + sessionFile);
        }

        // openFileOutput creates a file in /data/data/{packagename}/files/
        // In our case, /data/data/org.openintents.safe/files/
        // This file is owned and only readable by our application
        os = ctx.openFileOutput(sessionFile, Context.MODE_PRIVATE);

        // after writing the decrypted content to a temporary file,
        // pass back a Uri that can be used to read back the contents
        resultUri = Uri.withAppendedPath(CryptoContentProvider.CONTENT_URI, "decrypt/" + decryptSession);

        result = decryptStreamWithSessionKey(is, os);

        // Close the input stream
        is.close();
        os.close();

    } catch (FileNotFoundException e) {
        Log.e(TAG, "File not found", e);
    } catch (IOException e) {
        Log.e(TAG, "IOException", e);
    }

    if (result == false) {
        resultUri = null;

        // Unsuccessful. Clean up
        ctx.deleteFile(sessionFile);
    }

    return resultUri;
}

From source file:com.mozilla.SUTAgentAndroid.service.DoCommand.java

public String UpdateCallBack(String sFileName) {
    String sRet = sErrorPrefix + "No file specified";
    String sIP = "";
    String sPort = "";
    int nEnd = 0;
    int nStart = 0;

    if ((sFileName == null) || (sFileName.length() == 0))
        return (sRet);

    Context ctx = contextWrapper.getApplicationContext();
    try {/*from w  ww.  j  av a  2s  . c om*/
        FileInputStream fis = ctx.openFileInput(sFileName);
        int nBytes = fis.available();
        if (nBytes > 0) {
            byte[] buffer = new byte[nBytes + 1];
            int nRead = fis.read(buffer, 0, nBytes);
            fis.close();
            ctx.deleteFile(sFileName);
            if (nRead > 0) {
                String sBuffer = new String(buffer);
                nEnd = sBuffer.indexOf(',');
                if (nEnd > 0) {
                    sIP = (sBuffer.substring(0, nEnd)).trim();
                    nStart = nEnd + 1;
                    nEnd = sBuffer.indexOf('\r', nStart);
                    if (nEnd > 0) {
                        sPort = (sBuffer.substring(nStart, nEnd)).trim();
                        Thread.sleep(5000);
                        sRet = RegisterTheDevice(sIP, sPort, sBuffer.substring(nEnd + 1));
                    }
                }
            }
        }
    } catch (FileNotFoundException e) {
        sRet = sErrorPrefix + "Nothing to do";
    } catch (IOException e) {
        sRet = sErrorPrefix + "Couldn't send info to " + sIP + ":" + sPort;
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    return (sRet);
}

From source file:com.codename1.impl.android.AndroidImplementation.java

public static void firePendingPushes(final PushCallback c, final Context a) {
    try {/*from w  w w.j av  a  2s . c o m*/
        if (c != null) {
            InputStream i = a.openFileInput("CN1$AndroidPendingNotifications");
            if (i == null) {
                return;
            }
            DataInputStream is = new DataInputStream(i);
            int count = is.readByte();
            for (int iter = 0; iter < count; iter++) {
                boolean hasType = is.readBoolean();
                String actualType = null;
                if (hasType) {
                    actualType = is.readUTF();
                }
                final String t;
                final String b;
                final String category;
                final String image;
                if ("99".equals(actualType)) {
                    // This was a rich push
                    Map<String, String> vals = splitQuery(is.readUTF());
                    t = vals.get("type");
                    b = vals.get("body");
                    category = vals.get("category");
                    image = vals.get("image");
                } else {
                    t = actualType;
                    b = is.readUTF();
                    category = null;
                    image = null;
                }
                long s = is.readLong();
                Display.getInstance().callSerially(new Runnable() {
                    @Override
                    public void run() {
                        Display.getInstance().setProperty("pendingPush", "true");
                        Display.getInstance().setProperty("pushType", t);
                        initPushContent(b, image, t, category, a);
                        if (t != null && ("3".equals(t) || "6".equals(t))) {
                            String[] a = b.split(";");
                            c.push(a[0]);
                            c.push(a[1]);
                        } else if (t != null && ("101".equals(t))) {
                            c.push(b.substring(b.indexOf(" ") + 1));
                        } else {
                            c.push(b);
                        }
                        Display.getInstance().setProperty("pendingPush", null);
                    }
                });
            }
            a.deleteFile("CN1$AndroidPendingNotifications");
        }
    } catch (IOException err) {
    }
}