Example usage for android.content Context MODE_APPEND

List of usage examples for android.content Context MODE_APPEND

Introduction

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

Prototype

int MODE_APPEND

To view the source code for android.content Context MODE_APPEND.

Click Source Link

Document

File creation mode: for use with #openFileOutput , if the file already exists then write data to the end of the existing file instead of erasing it.

Usage

From source file:com.appnexus.opensdkapp.MainActivity.java

synchronized public void writeToFile(String message) {
    PrintWriter out = null;// w w  w . jav  a2s . com
    try {
        out = new PrintWriter(openFileOutput(Constants.LOG_FILENAME, Context.MODE_APPEND));
        out.println(message);
    } catch (IOException e) {
        Log.e(Constants.BASE_LOG_TAG, "IOException when writing to log file", e);
    } finally {
        if (out != null)
            out.close();
    }
}

From source file:com.mobilyzer.MeasurementScheduler.java

/**
 * Save the results of a task to a file, for later uploading. This way, if the application
 * crashes, is halted, etc. between the task and checkin, no results are lost.
 * //from   w  ww  . ja v  a  2 s .  c  o m
 * @param result The JSON representation of a result, as a string
 */
private synchronized void saveResultToFile(String result) {
    try {
        Logger.i("Saving result to file...");
        BufferedOutputStream writer = new BufferedOutputStream(
                openFileOutput("results", Context.MODE_PRIVATE | Context.MODE_APPEND));
        result += "\n";
        Logger.d("Measurement size in byte: " + result.length());
        writer.write(result.getBytes());
        writer.close();
    } catch (FileNotFoundException e) {
        Logger.e("saveResultToFile->", e);
    } catch (IOException e) {
        Logger.e("saveResultToFile->", e);
    }
}

From source file:com.example.research.whatis.MainActivity.java

public String invokeSynonymsAPI() throws IOException, JSONException {
    if (OCRedText.length() > 0) {
        final ProgressDialog dialog = ProgressDialog.show(MainActivity.this, "Loading ...",
                "Fetching synonym for " + OCRedText, true, false);
        final Thread thread = new Thread(new Runnable() {
            @Override/*from   w  w w . jav a2  s  .c  o m*/
            public void run() {
                String synonymURL = "http://words.bighugelabs.com/api/2/4bbcc4ae52f1e82bd08e683a72665f7b/";

                synonymURL += OCRedText.toString() + "/json";
                synonymURL = synonymURL.replaceAll("\\s", "");

                Log.d("API", "Invokes Synonyms" + synonymURL);

                URL url = null;
                try {
                    url = new URL(synonymURL);
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setDoOutput(true);
                    connection.setDoInput(true);
                    connection.setRequestMethod("GET");

                    connection.setRequestProperty("Content-Type", "application/json");
                    //connection.setRequestProperty("Content-Length", Integer.toString(OCRedText.length()));

                    OutputStream stream = connection.getOutputStream();
                    stream.close();

                    //fabulous/json

                    httpCode = connection.getResponseCode();

                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (ProtocolException e) {
                    e.printStackTrace();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                // Doing UI related code in UI thread
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dialog.dismiss();
                        // Success request
                        try {
                            if (httpCode == HttpURLConnection.HTTP_OK) {
                                // Get response stream
                                String jsonResponse = GetResponseToString(connection.getInputStream());
                                JSONObject reader = new JSONObject(jsonResponse);
                                Log.d("Synonyms JSONResp ", jsonResponse.toString());
                                Log.d("Synonyms Reader", reader.toString());

                                JSONArray text = null;
                                try {
                                    JSONObject obj = reader.getJSONObject("adjective");
                                    text = obj.getJSONArray("syn");
                                } catch (JSONException e) {
                                    e.printStackTrace();

                                    try {
                                        JSONObject obj = reader.getJSONObject("noun");
                                        text = obj.getJSONArray("syn");
                                    } catch (JSONException e1) {
                                        JSONObject obj = reader.getJSONObject("verb");
                                        text = obj.getJSONArray("syn");
                                    }
                                }

                                if (text != null) {
                                    synonym = text.get(0).toString();
                                } else {
                                    synonym = "<ERROR IN API>";
                                }

                                FileOutputStream fos = openFileOutput("synonym.txt", Context.MODE_APPEND);
                                fos.write(synonym.getBytes());
                                fos.close();
                            } else {
                                // Error occurred
                                String jsonResponse = GetResponseToString(connection.getErrorStream());

                                JSONObject reader = new JSONObject(jsonResponse);
                                JSONArray text = reader.getJSONArray("ErrorMessage");

                                synonym = text.get(0).toString();
                                // Error message
                                //                                    Toast.makeText(MainActivity.this, "Error Message: " + synonym, Toast.LENGTH_LONG).show();
                                System.out.println();
                            }

                            connection.disconnect();

                            TextView view = (TextView) findViewById(R.id.textView);
                            view.setVisibility(View.VISIBLE);
                            ListView lView = (ListView) findViewById(R.id.listView);
                            lView.setVisibility(View.GONE);

                            view.setText(OCRedText + ":" + synonym);
                            dbHelper.insertWord(OCRedText, synonym, "", "http://words.bighugelabs.com");
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        });
        thread.start();
    } else {
        synonym = "";
    }

    return synonym;
}

From source file:com.mobiperf.MeasurementScheduler.java

/**
 * Save the results of a task to a file, for later uploading.
 * This way, if the application crashes, is halted, etc. between the
 * task and checkin, no results are lost.
 * /*w w w. j a va 2 s. c om*/
 * @param result The JSON representation of a result, as a string
 */
private synchronized void saveResultToFile(String result) {
    try {
        Logger.i("Saving result to file...");
        BufferedOutputStream writer = new BufferedOutputStream(
                openFileOutput("results", Context.MODE_PRIVATE | Context.MODE_APPEND));
        result += "\n";
        writer.write(result.getBytes());
        writer.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:net.kidlogger.kidlogger.KLService.java

protected void writeLogs(String fileType, byte[] lBuff) {
    String fName = file + fileType;
    File path = getFilesDir();/*  ww w .j  a v a 2  s  . c  o  m*/
    File f = new File(path, fName);
    // Creates the file if it doesn't exist
    if (!f.exists()) {
        String devId = android.provider.Settings.System.getString(getContentResolver(),
                android.provider.Settings.System.ANDROID_ID);
        byte[] buff = Templates.getHeader(devId);
        try {
            //path.mkdir();         
            //FileOutputStream fos = new FileOutputStream(f);
            FileOutputStream fos = openFileOutput(f.getName(), Context.MODE_PRIVATE);
            fos.write(buff);
            fos.close();
        } catch (IOException e) {
            app.logError(CN + "writeLogs", e.toString());
        } catch (SecurityException e) {
            app.logError(CN + "writeLogs", e.toString());
        }
    }

    // Add log to the file
    try {
        FileOutputStream fos = openFileOutput(fName, Context.MODE_APPEND);
        fos.write(lBuff);
        fos.close();
    } catch (IOException e) {
        app.logError(CN + "writeLogs", e.toString());
    }
}

From source file:self.philbrown.droidQuery.$.java

/**
 * Write a String to file, and execute functions once complete. 
 * @param s the String to write to the file
 * @param path defines the save location of the file
 * @param append {@code true} to append the new String to the end of the file. {@code false} to overwrite any existing file.
 * @param async {@code true} if the operation should be performed asynchronously. Otherwise, {@code false}.
 * @param success Function to invoke on a successful file-write. Parameters received will be:
 * <ol>//from  ww  w  .  j a v  a2  s  . c  om
 * <li>the String to write
 * <li>the File that was written (to)
 * </ol>
 * @param error Function to invoke on a file I/O error. Parameters received will be:
 * <ol>
 * <li>the String to write
 * <li>the String reason
 * </ol>
 */
public void write(final String s, final FileLocation path, final String fileName, boolean append, boolean async,
        final Function success, Function error) {
    boolean hasWritePermissions = false;
    try {
        PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(),
                PackageManager.GET_PERMISSIONS);
        if (info.requestedPermissions != null) {
            for (String p : info.requestedPermissions) {
                if (p.equals("android.permission.WRITE_EXTERNAL_STORAGE")) {
                    hasWritePermissions = true;
                    break;
                }
            }
        }
    } catch (Exception e) {
        if (error != null) {
            error.invoke(this, s, "Invalid Project Package!");
        }
        return;
    }
    if (!hasWritePermissions) {
        if (error != null) {
            error.invoke(this, s,
                    "You do not have file write privelages. Add the android.permission.WRITE_EXTERNAL_STORAGE permission to your Android Manifest.");
        }
        return;
    }

    File logFile;

    if (path == FileLocation.INTERNAL) {
        if (fileName.contains("\\")) {
            if (error != null) {
                error.invoke(this, s, "Internal file names cannot include a path separator. Aborting.");
            }
            return;
        }
        try {
            if (fileObservers == null) {
                fileObservers = new ArrayList<LogFileObserver>();
            }
            LogFileObserver o = new LogFileObserver(fileName, new Runnable() {
                @Override
                public void run() {
                    if (success != null)
                        success.invoke($.this, s, new File(
                                String.format(Locale.US, "%s/%s", context.getFilesDir().getName(), fileName)));
                }
            });
            fileObservers.add(o);
            o.startWatching();

            FileOutputStream fw = context.openFileOutput(fileName,
                    (append ? Context.MODE_APPEND : Context.MODE_PRIVATE));
            fw.write(s.getBytes());
            fw.close();
        } catch (Throwable t) {
            t.printStackTrace();
        }
        return;
    } else if (path == FileLocation.CACHE) {
        String storageDir = context.getCacheDir().toString();

        logFile = new File(String.format(Locale.US, "%s/%s", storageDir, fileName));
        //make the parent directory if it does not exist
        logFile.getParentFile().mkdirs();
    } else if (path == FileLocation.DATA) {
        String storageDir = Environment.getExternalStorageDirectory().toString();
        String mainDirName = String.format(Locale.US, "%s/Android/data/%s", storageDir,
                context.getPackageName());

        logFile = new File(String.format(Locale.US, "%s/%s", mainDirName, fileName));
        //make the parent directory if it does not exist
        logFile.getParentFile().mkdirs();
    } else if (path == FileLocation.CUSTOM) {
        logFile = new File(fileName);
        //make the parent directory if it does not exist
        logFile.getParentFile().mkdirs();
    } else //external (default)
    {
        String storageDir = Environment.getExternalStorageDirectory().toString();
        String mainDirName = String.format(Locale.US, "%s/%s", storageDir, context.getPackageName());

        logFile = new File(String.format(Locale.US, "%s/%s", mainDirName, fileName));
        //make the parent directory if it does not exist
        logFile.getParentFile().mkdirs();
    }

    try {
        if (fileObservers == null) {
            fileObservers = new ArrayList<LogFileObserver>();
        }
        final File fLogFile = logFile;
        LogFileObserver o = new LogFileObserver(logFile, new Runnable() {
            @Override
            public void run() {
                if (success != null)
                    success.invoke($.this, s, fLogFile);
            }
        });

        fileObservers.add(o);
        o.startWatching();

        FileOutputStream os = new FileOutputStream(logFile, append);
        os.write(s.getBytes());
        os.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:self.philbrown.droidQuery.$.java

/**
 * Write a byte stream to file, and execute functions once complete. 
 * @param s the bytes to write to the file
 * @param path defines the save location of the file
 * @param append {@code true} to append the new bytes to the end of the file. {@code false} to overwrite any existing file.
 * @param async {@code true} if the operation should be performed asynchronously. Otherwise, {@code false}.
 * @param success Function to invoke on a successful file-write. Parameters received will be:
 * <ol>// w  w w.j  av a2s.c o  m
 * <li>the byte[] to write
 * <li>the path to the file
 * </ol>
 * @param error Function to invoke on a file I/O error. Parameters received will be:
 * <ol>
 * <li>the byte[] to write
 * <li>the path to the file
 * </ol>
 */
public void write(final byte[] s, final FileLocation path, String fileName, boolean append, boolean async,
        final Function success, Function error) {
    boolean hasWritePermissions = false;
    try {
        PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(),
                PackageManager.GET_PERMISSIONS);
        if (info.requestedPermissions != null) {
            for (String p : info.requestedPermissions) {
                if (p.equals("android.permission.WRITE_EXTERNAL_STORAGE")) {
                    hasWritePermissions = true;
                    break;
                }
            }
        }
    } catch (Exception e) {
        if (error != null) {
            error.invoke(this, s, path, "Invalid Project Package!");
        }
        return;
    }
    if (!hasWritePermissions) {
        if (error != null) {
            error.invoke(this, s, path,
                    "You do not have file write privelages. Add the android.permission.WRITE_EXTERNAL_STORAGE permission to your Android Manifest.");
        }
        return;
    }

    File logFile;

    if (path == FileLocation.INTERNAL) {
        if (fileName.contains("\\")) {
            if (error != null) {
                error.invoke(this, s, path, "Internal file names cannot include a path separator. Aborting.");
            }
            return;
        }
        try {
            if (fileObservers == null) {
                fileObservers = new ArrayList<LogFileObserver>();
            }
            LogFileObserver o = new LogFileObserver(fileName, new Runnable() {
                @Override
                public void run() {
                    if (success != null)
                        success.invoke($.this, s, path);
                }
            });
            fileObservers.add(o);
            o.startWatching();

            FileOutputStream fw = context.openFileOutput(fileName,
                    (append ? Context.MODE_APPEND : Context.MODE_PRIVATE));
            fw.write(s);
            fw.close();
        } catch (Throwable t) {
            t.printStackTrace();
        }
        return;
    } else if (path == FileLocation.CACHE) {
        String storageDir = context.getCacheDir().toString();

        logFile = new File(String.format(Locale.US, "%s/%s", storageDir, fileName));
        //make the parent directory if it does not exist
        logFile.getParentFile().mkdirs();
    } else if (path == FileLocation.DATA) {
        String storageDir = Environment.getExternalStorageDirectory().toString();
        String mainDirName = String.format(Locale.US, "%s/Android/data/%s", storageDir,
                context.getPackageName());

        logFile = new File(String.format(Locale.US, "%s/%s", mainDirName, fileName));
        //make the parent directory if it does not exist
        logFile.getParentFile().mkdirs();
    } else if (path == FileLocation.CUSTOM) {
        logFile = new File(fileName);
        //make the parent directory if it does not exist
        logFile.getParentFile().mkdirs();
    } else //external (default)
    {
        String storageDir = Environment.getExternalStorageDirectory().toString();
        String mainDirName = String.format(Locale.US, "%s/%s", storageDir, context.getPackageName());

        logFile = new File(String.format(Locale.US, "%s/%s", mainDirName, fileName));
        //make the parent directory if it does not exist
        logFile.getParentFile().mkdirs();
    }

    try {
        if (fileObservers == null) {
            fileObservers = new ArrayList<LogFileObserver>();
        }
        LogFileObserver o = new LogFileObserver(logFile, new Runnable() {
            @Override
            public void run() {
                if (success != null)
                    success.invoke($.this, s, path);
            }
        });

        fileObservers.add(o);
        o.startWatching();

        FileOutputStream os = new FileOutputStream(logFile, append);
        os.write(s);
        os.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}