Example usage for android.content Context openFileOutput

List of usage examples for android.content Context openFileOutput

Introduction

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

Prototype

public abstract FileOutputStream openFileOutput(String name, @FileMode int mode) throws FileNotFoundException;

Source Link

Document

Open a private file associated with this Context's application package for writing.

Usage

From source file:com.mhise.util.MHISEUtil.java

public static void writeKey(PrivateKey pKey, Context context) throws Exception {

    String keyFile = "privateKey.key";
    FileOutputStream fos = context.openFileOutput(keyFile, Context.MODE_PRIVATE);
    byte[] kb = pKey.getEncoded();
    fos.write(kb);/*from w w  w.j ava 2s .  com*/
    fos.close();

}

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  .j a  v a 2  s .c o m
 * @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:br.ufrgs.urbosenti.test.TestManager.java

public TestManager(DeviceManager deviceManager, String filesName, Context context) throws IOException {
    super(deviceManager, COMPONENT_ID);
    this.deviceManager = deviceManager;
    FileOutputStream outputStream = context.openFileOutput("actionResults" + filesName + ".out",
            Context.MODE_WORLD_READABLE);

    //this.experimentalResults = new FileWriter(new File("actionResults" + filesName + ".out"));
    this.writer = outputStream;
    this.shudown = false;
    this.eventCount = 0;
    this.eventLimit = 1;
    this.interactionMode = 0;
}

From source file:li.klass.fhem.service.room.RoomListHolderService.java

private void storeDeviceListMapInternal(RoomDeviceList roomDeviceList, Context context) {
    fillHiddenRoomsAndHiddenGroups(roomDeviceList, findFHEMWEBDevice(roomDeviceList, context));
    cachedRoomList = roomDeviceList;/*from  w  ww .  ja v  a  2  s.c  om*/
    LOG.info("storeDeviceListMap() : storing device list to cache");
    long startLoad = System.currentTimeMillis();
    ObjectOutputStream objectOutputStream = null;
    try {
        objectOutputStream = new ObjectOutputStream(
                new BufferedOutputStream(context.openFileOutput(CACHE_FILENAME, Context.MODE_PRIVATE)));
        objectOutputStream.writeObject(roomDeviceList);
        fileStoreNotFilled = false;
        LOG.info("storeDeviceListMap() : storing device list to cache completed after {} ms",
                (System.currentTimeMillis() - startLoad));
    } catch (Exception e) {
        LOG.error("storeDeviceListMap() : error occurred while writing data to disk", e);
    } finally {
        CloseableUtil.close(objectOutputStream);
    }
}

From source file:com.apptentive.android.sdk.model.FileMessage.java

public boolean createStoredFile(Context context, InputStream is, String mimeType) throws IOException {
    setMimeType(mimeType);/*from   w ww  .  j  av  a 2 s . c om*/

    // Create a file to save locally.
    String localFileName = getStoredFileId();
    File localFile = new File(localFileName);

    // Copy the file contents over.
    CountingOutputStream os = null;
    try {
        os = new CountingOutputStream(
                new BufferedOutputStream(context.openFileOutput(localFile.getPath(), Context.MODE_PRIVATE)));
        byte[] buf = new byte[2048];
        int count;
        while ((count = is.read(buf, 0, 2048)) != -1) {
            os.write(buf, 0, count);
        }
        Log.d("File saved, size = " + (os.getBytesWritten() / 1024) + "k");
    } finally {
        Util.ensureClosed(os);
    }

    // Create a StoredFile database entry for this locally saved file.
    StoredFile storedFile = new StoredFile();
    storedFile.setId(getStoredFileId());
    storedFile.setLocalFilePath(localFile.getPath());
    storedFile.setMimeType(mimeType);
    FileStore db = ApptentiveDatabase.getInstance(context);
    return db.putStoredFile(storedFile);
}

From source file:reco.frame.tv.http.entityhandler.FileEntityHandler.java

public Object handleEntity(Context appContext, HttpEntity entity, EntityCallBack callback, String target,
        boolean isResume) throws IOException {
    if (TextUtils.isEmpty(target) || target.trim().length() == 0)
        return null;

    File targetFile = new File(target);

    if (!targetFile.exists()) {
        targetFile.createNewFile();//  w  w  w.j  av a  2 s  .  c  o  m
    }

    if (mStop) {
        return targetFile;
    }

    long current = 0;
    FileOutputStream os = null;
    if (isResume) {
        current = targetFile.length();
        os = appContext.openFileOutput(target.substring(target.lastIndexOf("/") + 1),
                Context.MODE_APPEND | Context.MODE_WORLD_READABLE);
        //os = new FileOutputStream(target, true);
    } else {
        os = appContext.openFileOutput(target.substring(target.lastIndexOf("/") + 1),
                Context.MODE_WORLD_READABLE);
    }

    if (mStop) {
        return targetFile;
    }

    InputStream input = entity.getContent();
    long count = entity.getContentLength() + current;

    if (current >= count || mStop) {
        return targetFile;
    }

    int readLen = 0;
    byte[] buffer = new byte[1024];
    while (!mStop && !(current >= count) && ((readLen = input.read(buffer, 0, 1024)) > 0)) {//
        os.write(buffer, 0, readLen);
        current += readLen;
        callback.callBack(count, current, false);
    }
    callback.callBack(count, current, true);

    if (mStop && current < count) { //
        throw new IOException("user stop download thread");
    }

    return targetFile;
}

From source file:com.panoskrt.dbadapter.DBAdapter.java

public void downloadDB(Context context, String dbName, String urlLink) {
    try {/*from w ww  .  j a  va 2s.co  m*/
        URL url = new URL(urlLink);
        URLConnection ucon = url.openConnection();

        InputStream is = ucon.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(is);
        ByteArrayBuffer baf = new ByteArrayBuffer(50);

        int current = 0;
        while ((current = bis.read()) != -1) {
            baf.append((byte) current);
        }

        FileOutputStream fos = context.openFileOutput(dbName, Context.MODE_PRIVATE);
        fos.write(baf.toByteArray());
        fos.close();

        File dbFile = new File(context.getFilesDir() + "/" + dbName);
        InputStream in = new FileInputStream(dbFile);
        OutputStream out = new FileOutputStream(dbPath + dbName);
        bufCopy(in, out);
        dbFile.delete();

    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

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   ww w.j a  va2 s . c om*/
        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:net.phase.wallet.Currency.java

public static void saveWallets(Wallet[] wallets, Context context) throws IOException {
    for (Wallet w : wallets) {
        PrintWriter out = new PrintWriter(
                new OutputStreamWriter(context.openFileOutput(w.name, Context.MODE_PRIVATE)));
        w.SaveWallet(out);//from   w  w w.  jav a2s .c  om
        out.close();
    }
}