android.content.Context.openFileOutput()方法的使用及代码示例

x33g5p2x  于2022-01-17 转载在 其他  
字(10.0k)|赞(0)|评价(0)|浏览(160)

本文整理了Java中android.content.Context.openFileOutput()方法的一些代码示例,展示了Context.openFileOutput()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Context.openFileOutput()方法的具体详情如下:
包路径:android.content.Context
类名称:Context
方法名:openFileOutput

Context.openFileOutput介绍

暂无

代码示例

代码示例来源:origin: oasisfeng/condom

@Override public FileOutputStream openFileOutput(String name, int mode) throws FileNotFoundException {
  return mBase.openFileOutput(name, mode);
}

代码示例来源:origin: stackoverflow.com

private void writeToFile(String data,Context context) {
  try {
    OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput("config.txt", Context.MODE_PRIVATE));
    outputStreamWriter.write(data);
    outputStreamWriter.close();
  }
  catch (IOException e) {
    Log.e("Exception", "File write failed: " + e.toString());
  } 
}

代码示例来源:origin: stackoverflow.com

public void saveImage(Context context, Bitmap b,String name,String extension){
  name=name+"."+extension;
  FileOutputStream out;
  try {
    out = context.openFileOutput(name, Context.MODE_PRIVATE);
    b.compress(Bitmap.CompressFormat.JPEG, 90, out);
    out.close();
  } catch (Exception e) {
    e.printStackTrace();
  }
}

代码示例来源:origin: stackoverflow.com

public static void save(String filename, MyObjectClassArray[] theObjectAr, 
Context ctx) {
   FileOutputStream fos;
   try {
     fos = ctx.openFileOutput(filename, Context.MODE_PRIVATE);
     ObjectOutputStream oos = new ObjectOutputStream(fos);
     oos.writeObject(theObjectAr); 
     oos.close();
   } catch (FileNotFoundException e) {
     e.printStackTrace();
   }catch(IOException e){
     e.printStackTrace();
   }
 }

代码示例来源:origin: avjinder/Minimal-Todo

public void saveToFile(ArrayList<ToDoItem> items) throws JSONException, IOException {
  FileOutputStream fileOutputStream;
  OutputStreamWriter outputStreamWriter;
  fileOutputStream = mContext.openFileOutput(mFileName, Context.MODE_PRIVATE);
  outputStreamWriter = new OutputStreamWriter(fileOutputStream);
  outputStreamWriter.write(toJSONArray(items).toString());
  outputStreamWriter.close();
  fileOutputStream.close();
}

代码示例来源:origin: facebook/stetho

public OutputStream openResponseBodyFile(String requestId, boolean base64Encode)
  throws IOException {
 OutputStream out = mContext.openFileOutput(getFilename(requestId), Context.MODE_PRIVATE);
 out.write(base64Encode ? 1 : 0);
 if (base64Encode) {
  return new Base64OutputStream(out, Base64.DEFAULT);
 } else {
  return out;
 }
}

代码示例来源:origin: stackoverflow.com

private boolean copyFile(Context context,String fileName) {
   boolean status = false;
   try { 
     FileOutputStream out = context.openFileOutput(fileName, Context.MODE_PRIVATE);
     InputStream in = context.getAssets().open(fileName);
     // Transfer bytes from the input file to the output file
     byte[] buf = new byte[1024];
     int len;
     while ((len = in.read(buf)) > 0) {
       out.write(buf, 0, len);
     }
     // Close the streams
     out.close();
     in.close();
     status = true;
   } catch (Exception e) {
     System.out.println("Exception in copyFile:: "+e.getMessage());
     status = false;
   }
   System.out.println("copyFile Status:: "+status);
   return status;
 }

代码示例来源:origin: facebook/facebook-android-sdk

static void saveAppSessionInformation(Context context) {
  ObjectOutputStream oos = null;
  synchronized (staticLock) {
    if (hasChanges) {
      try {
        oos = new ObjectOutputStream(
            new BufferedOutputStream(
                context.openFileOutput(
                    PERSISTED_SESSION_INFO_FILENAME,
                    Context.MODE_PRIVATE)
            )
        );
        oos.writeObject(appSessionInfoMap);
        hasChanges = false;
        Logger.log(
            LoggingBehavior.APP_EVENTS,
            "AppEvents",
            "App session info saved");
      } catch (Exception e) {
        Log.w(
            TAG,
            "Got unexpected exception while writing app session info: "
                + e.toString());
      } finally {
        Utility.closeQuietly(oos);
      }
    }
  }
}

代码示例来源:origin: facebook/facebook-android-sdk

private static void saveEventsToDisk(
    PersistedEvents eventsToPersist) {
  ObjectOutputStream oos = null;
  Context context = FacebookSdk.getApplicationContext();
  try {
    oos = new ObjectOutputStream(
        new BufferedOutputStream(
            context.openFileOutput(PERSISTED_EVENTS_FILENAME, 0)));
    oos.writeObject(eventsToPersist);
  } catch (Exception e) {
    Log.w(TAG, "Got unexpected exception while persisting events: ", e);
    try {
      context.getFileStreamPath(PERSISTED_EVENTS_FILENAME).delete();
    } catch (Exception innerException) {
      // ignore
    }
  } finally {
    Utility.closeQuietly(oos);
  }
}

代码示例来源:origin: AltBeacon/android-beacon-library

private boolean saveJson(String jsonString) {
  FileOutputStream outputStream = null;
  try {
    outputStream = mContext.openFileOutput(CONFIG_FILE, Context.MODE_PRIVATE);
    outputStream.write(jsonString.getBytes());
    outputStream.close();
  } catch (Exception e) {
    LogManager.w(e, TAG, "Cannot write updated distance model to local storage");
    return false;
  }
  finally {
    try {
      if (outputStream != null) outputStream.close();
    }
    catch (Exception e) {}
  }
  LogManager.i(TAG, "Successfully saved new distance model file");
  return true;
}

代码示例来源:origin: AltBeacon/android-beacon-library

private void saveState() {
  FileOutputStream outputStream;
  OutputStreamWriter writer = null;
  lastStateSaveTime = SystemClock.elapsedRealtime();
  try {
    outputStream = context.openFileOutput(DISTINCT_BLUETOOTH_ADDRESSES_FILE, Context.MODE_PRIVATE);
    writer = new OutputStreamWriter(outputStream);
    writer.write(lastBluetoothCrashDetectionTime+"\n");
    writer.write(detectedCrashCount+"\n");
    writer.write(recoveryAttemptCount+"\n");
    writer.write(lastRecoverySucceeded ? "1\n" : "0\n");
    synchronized (distinctBluetoothAddresses) {
      for (String mac : distinctBluetoothAddresses) {
        writer.write(mac);
        writer.write("\n");
      }
    }
  } catch (IOException e) {
    LogManager.w(TAG, "Can't write macs to %s", DISTINCT_BLUETOOTH_ADDRESSES_FILE);
  }
  finally {
    if (writer != null) {
      try {
        writer.close();
      } catch (IOException e1) { }
    }
  }
  LogManager.d(TAG, "Wrote %s Bluetooth addresses", distinctBluetoothAddresses.size());
}

代码示例来源:origin: robolectric/robolectric

@Test(expected = IllegalArgumentException.class)
public void openFileOutput_shouldNotAcceptPathsWithSeparatorCharacters() throws Exception {
 try (FileOutputStream fos = context.openFileOutput(File.separator + "data" + File.separator + "test" + File.separator + "hi", 0)) {}
}

代码示例来源:origin: robolectric/robolectric

@Test
public void openFileOutput_shouldReturnAFileOutputStream() throws Exception {
 File file = new File("__test__");
 String fileContents = "blah";
 try (FileOutputStream fileOutputStream = context.openFileOutput("__test__", Context.MODE_PRIVATE)) {
  fileOutputStream.write(fileContents.getBytes(UTF_8));
 }
 try (FileInputStream fileInputStream = new FileInputStream(new File(context.getFilesDir(), file.getName()))) {
  byte[] readBuffer = new byte[fileContents.length()];
  fileInputStream.read(readBuffer);
  assertThat(new String(readBuffer, UTF_8)).isEqualTo(fileContents);
 }
}

代码示例来源:origin: robolectric/robolectric

@Test
public void openFileOutput_shouldAppendData() throws Exception {
 File file = new File("__test__");
 String initialFileContents = "foo";
 String appendedFileContents = "bar";
 String finalFileContents = initialFileContents + appendedFileContents;
 try (FileOutputStream fileOutputStream = context.openFileOutput("__test__", Context.MODE_APPEND)) {
  fileOutputStream.write(initialFileContents.getBytes(UTF_8));
 }
 try (FileOutputStream fileOutputStream = context.openFileOutput("__test__", Context.MODE_APPEND)) {
  fileOutputStream.write(appendedFileContents.getBytes(UTF_8));
 }
 try (FileInputStream fileInputStream = new FileInputStream(new File(context.getFilesDir(), file.getName()))) {
  byte[] readBuffer = new byte[finalFileContents.length()];
  fileInputStream.read(readBuffer);
  assertThat(new String(readBuffer, UTF_8)).isEqualTo(finalFileContents);
 }
}

代码示例来源:origin: robolectric/robolectric

@Test
public void openFileOutput_shouldOverwriteData() throws Exception {
 File file = new File("__test__");
 String initialFileContents = "foo";
 String newFileContents = "bar";
 try (FileOutputStream fileOutputStream = context.openFileOutput("__test__", 0)) {
  fileOutputStream.write(initialFileContents.getBytes(UTF_8));
 }
 try (FileOutputStream fileOutputStream = context.openFileOutput("__test__", 0)) {
  fileOutputStream.write(newFileContents.getBytes(UTF_8));
 }
 try (FileInputStream fileInputStream = new FileInputStream(new File(context.getFilesDir(), file.getName()))) {
  byte[] readBuffer = new byte[newFileContents.length()];
  fileInputStream.read(readBuffer);
  assertThat(new String(readBuffer, UTF_8)).isEqualTo(newFileContents);
 }
}

代码示例来源:origin: AltBeacon/android-beacon-library

ObjectOutputStream objectOutputStream = null;
try {
  outputStream = mContext.openFileOutput(TEMP_STATUS_PRESERVATION_FILE_NAME, MODE_PRIVATE);
  objectOutputStream = new ObjectOutputStream(outputStream);
  objectOutputStream.writeObject(this);

代码示例来源:origin: AltBeacon/android-beacon-library

ObjectOutputStream objectOutputStream = null;
try {
  outputStream = mContext.openFileOutput(STATUS_PRESERVATION_FILE_NAME, MODE_PRIVATE);
  objectOutputStream = new ObjectOutputStream(outputStream);
  Map<Region,RegionMonitoringState> map = getRegionsStateMap();

代码示例来源:origin: westnordost/StreetComplete

private void writeCrashReportToFile(String text)
{
  try(FileOutputStream fos = appCtx.openFileOutput(CRASHREPORT, Context.MODE_PRIVATE))
  {
    fos.write(text.getBytes(ENC));
  }
  catch (IOException ignored) {}
}

代码示例来源:origin: julian-klode/dns66

/**
 * Write to the given file in the private files dir, first renaming an old one to .bak
 *
 * @param context  A context
 * @param filename A filename as for @{link {@link Context#openFileOutput(String, int)}}
 * @return See @{link {@link Context#openFileOutput(String, int)}}
 * @throws IOException See @{link {@link Context#openFileOutput(String, int)}}
 */
public static OutputStream openWrite(Context context, String filename) throws IOException {
  File out = context.getFileStreamPath(filename);
  // Create backup
  out.renameTo(context.getFileStreamPath(filename + ".bak"));
  return context.openFileOutput(filename, Context.MODE_PRIVATE);
}

代码示例来源:origin: julian-klode/dns66

@Test
public void testOpenWrite() throws Exception {
  File file = mock(File.class);
  File file2 = mock(File.class);
  FileOutputStream fos = mock(FileOutputStream.class);
  when(mockContext.getFileStreamPath(eq("filename"))).thenReturn(file);
  when(mockContext.getFileStreamPath(eq("filename.bak"))).thenReturn(file2);
  when(mockContext.openFileOutput(eq("filename"), anyInt())).thenReturn(fos);
  assertSame(fos, FileHelper.openWrite(mockContext, "filename"));
  Mockito.verify(file).renameTo(file2);
  Mockito.verify(mockContext).openFileOutput(eq("filename"), anyInt());
}

相关文章

微信公众号

最新文章

更多

Context类方法