下面列出了android.content.Context#openFileInput ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private void loadVPNList(Context context) {
profiles = new HashMap<>();
SharedPreferences listpref = context.getSharedPreferences(PREFS_NAME, Activity.MODE_PRIVATE);
Set<String> vlist = listpref.getStringSet("vpnlist", null);
if (vlist == null) {
vlist = new HashSet<>();
}
for (String vpnentry : vlist) {
try {
ObjectInputStream vpnfile = new ObjectInputStream(context.openFileInput(vpnentry + ".vp"));
VpnProfile vp = ((VpnProfile) vpnfile.readObject());
// Sanity check
if (vp == null || vp.mName == null || vp.getUUID() == null) continue;
vp.upgradeProfile();
profiles.put(vp.getUUID().toString(), vp);
} catch (IOException | ClassNotFoundException e) {
VpnStatus.logException("Loading VPN List", e);
}
}
}
/**
* Upgrade table.
*
* @param db {@link SQLiteDatabase}
* @throws IOException IOException
*/
public static void onUpgrade(final Context context, final SQLiteDatabase db)
throws IOException {
Log.w(TAG, "Upgrading table: " + TABLE);
String fn = TABLE + ".bak";
context.deleteFile(fn);
ObjectOutputStream os = new ObjectOutputStream(context.openFileOutput(fn,
Context.MODE_PRIVATE));
backup(db, TABLE, PROJECTION, null, null, null, os);
os.close();
ObjectInputStream is = new ObjectInputStream(context.openFileInput(fn));
onCreate(db);
reload(db, TABLE, is);
is.close();
}
private void loadVPNList(Context context) {
profiles = new HashMap<>();
SharedPreferences listpref = context.getSharedPreferences(PREFS_NAME, Activity.MODE_PRIVATE);
Set<String> vlist = listpref.getStringSet("vpnlist", null);
if (vlist == null) {
vlist = new HashSet<>();
}
for (String vpnentry : vlist) {
try {
ObjectInputStream vpnfile = new ObjectInputStream(context.openFileInput(vpnentry + ".vp"));
VpnProfile vp = ((VpnProfile) vpnfile.readObject());
// Sanity check
if (vp == null || vp.mName == null || vp.getUUID() == null)
continue;
vp.upgradeProfile();
profiles.put(vp.getUUID().toString(), vp);
} catch (IOException | ClassNotFoundException e) {
VpnStatus.logException("Loading VPN List", e);
}
}
}
public static PinnedBlockedApps getInstance(Context context) {
if(theInstance == null)
try {
FileInputStream fileInputStream = context.openFileInput("PinnedBlockedApps");
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
theInstance = (PinnedBlockedApps) objectInputStream.readObject();
objectInputStream.close();
fileInputStream.close();
} catch (IOException | ClassNotFoundException e) {
theInstance = new PinnedBlockedApps();
}
return theInstance;
}
private void loadVPNList(Context context) {
profiles = new HashMap<>();
SharedPreferences listpref = context.getSharedPreferences(PREFS_NAME, Activity.MODE_PRIVATE);
Set<String> vlist = listpref.getStringSet("vpnlist", null);
if (vlist == null) {
vlist = new HashSet<>();
}
for (String vpnentry : vlist) {
try {
ObjectInputStream vpnfile = new ObjectInputStream(context.openFileInput(vpnentry + ".vp"));
VpnProfile vp = ((VpnProfile) vpnfile.readObject());
// Sanity check
if (vp == null || vp.mName == null || vp.getUUID() == null)
continue;
vp.upgradeProfile();
profiles.put(vp.getUUID().toString(), vp);
} catch (IOException | ClassNotFoundException e) {
VpnStatus.logException("Loading VPN List", e);
}
}
}
@Test
public void testWriteToFile() throws Exception {
final SettingsProto.Settings message = new SettingsProto.Settings();
message.scrobbleEnabled = true;
message.theme = 666;
final String fileName = "protoUtilsWriteToFile";
final Context context = RuntimeEnvironment.application;
// Delete old copies
context.deleteFile(fileName);
// Write actual file
ProtoUtils.writeToFile(context, fileName, message);
// Read
final InputStream is = context.openFileInput(fileName);
final byte[] readBytes = ByteStreams.toByteArray(is);
assertNotNull(readBytes);
// Create from read
final SettingsProto.Settings read = new SettingsProto.Settings()
.mergeFrom(CodedInputByteBufferNano.newInstance(readBytes));
// compare
assertEquals(message.scrobbleEnabled, read.scrobbleEnabled);
assertEquals(message.theme, read.theme);
}
@SuppressWarnings("unchecked")
private static void restoreAppSessionInformation(Context context) {
ObjectInputStream ois = null;
synchronized (staticLock) {
if (!isLoaded) {
try {
ois =
new ObjectInputStream(
context.openFileInput(PERSISTED_SESSION_INFO_FILENAME));
appSessionInfoMap =
(HashMap<AccessTokenAppIdPair, FacebookTimeSpentData>) ois.readObject();
Logger.log(
LoggingBehavior.APP_EVENTS,
"AppEvents",
"App session info loaded");
} catch (FileNotFoundException fex) {
} catch (Exception e) {
Log.d(TAG, "Got unexpected exception: " + e.toString());
} finally {
Utility.closeQuietly(ois);
context.deleteFile(PERSISTED_SESSION_INFO_FILENAME);
if (appSessionInfoMap == null) {
appSessionInfoMap =
new HashMap<AccessTokenAppIdPair, FacebookTimeSpentData>();
}
// Regardless of the outcome of the load, the session information cache
// is always deleted. Therefore, always treat the session information cache
// as loaded
isLoaded = true;
hasChanges = false;
}
}
}
}
/**
* 读取文本文件
*
* @param context
* @param fileName
* @return
*/
public static String read(Context context, String fileName) {
try {
FileInputStream in = context.openFileInput(fileName);
return readInStream(in);
} catch (Exception e) {
// e.printStackTrace();
return "";
}
}
public boolean iconCached(Context context) {
if (!hasIcon())
return false;
try {
context.openFileInput(MiscUtil.iconFilename(this.icon));
return true;
} catch (IOException ignore) {
return false;
}
}
public boolean iconCached(Context context) {
if (!hasIcon())
return false;
try {
context.openFileInput(MiscUtil.iconFilename(this.icon));
return true;
} catch (IOException ignore) {
return false;
}
}
public Bitmap loadImageBitmap(Context context, String imageName) {
Bitmap bitmap = null;
FileInputStream fiStream;
try {
fiStream = context.openFileInput(imageName);
bitmap = BitmapFactory.decodeStream(fiStream);
fiStream.close();
} catch (Exception e) {
Timber.e("Failed to load image from disk: %s", imageName);
e.printStackTrace();
}
return bitmap;
}
/**
* Reads data from the file in internal memory
*
* @param fileName File name
* @param context Context
* @return Read data
*/
public static String readInternalFile(String fileName, Context context) {
String dataFromFile = "";
File file = context.getFileStreamPath(fileName);
if (file.exists()) {
try {
InputStream inputStream = context.openFileInput(fileName);
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ((receiveString = bufferedReader.readLine()) != null) {
stringBuilder.append(receiveString);
}
inputStream.close();
dataFromFile = stringBuilder.toString();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return dataFromFile;
}
/**
* 读取文本文件
*
* @param context
* @param fileName
* @return
*/
public static String read(Context context, String fileName) {
try {
FileInputStream in = context.openFileInput(fileName);
return readInStream(in);
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
private InputStream bodyForUploadImage(InputStream image, String boundary, boolean isGif) {
try {
Context context = ZenApplication.getAppContext();
String boundaryNormal = "\r\n--" + boundary + "\r\n";
String boundaryEnd = "\r\n--" + boundary + "--\r\n";
String timestamp = ZenUtils.timestamp();
StringBuffer buf = new StringBuffer();
OutputStream out = context.openFileOutput("zen_upload", Context.MODE_PRIVATE);
buf.append(boundaryNormal)
.append("Content-Disposition: form-data; name=\"name\"\r\n\r\n"
+ timestamp + (isGif ? ".gif" : ".jpg"))
.append(boundaryNormal)
.append("Content-Disposition: form-data; name=\"pic_upload\"\r\n\r\n0")
.append(boundaryNormal)
.append("Content-Disposition: form-data; name=\"watermark\"\r\n\r\n0")
.append(boundaryNormal)
.append("Content-Disposition: form-data; name=\"albumId\"\r\n\r\ndefault")
.append(boundaryNormal)
.append("Content-Disposition: form-data; name=\"imagefile[]\"; filename=\""
+ timestamp
+ (isGif ? ".gif\"" : ".jpg\"") + "\r\nContent-Type: " + (isGif ? "image/gif\r\n\r\n" : "image/jpeg\r\n\r\n"));
out.write(buf.toString().getBytes("utf-8"));
byte[] buffer = new byte[1024];
int len = -1;
while( (len = image.read(buffer)) != -1 ){
out.write(buffer, 0, len);
}
image.close();
out.write(boundaryEnd.toString().getBytes("utf-8"));
out.close();
InputStream input = context.openFileInput("zen_upload");
return input;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 读取文本文件
*
* @param context
* @param fileName
* @return
*/
public static String read(Context context, String fileName) {
try {
FileInputStream in = context.openFileInput(fileName);
return readInStream(in);
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
public static Object readObject(String filename, Context context) {
Object t = null;
try {
FileInputStream fis = context.openFileInput(filename);
ObjectInputStream os = new ObjectInputStream(fis);
t = (Object) os.readObject();
os.close();
} catch (Exception e) {
//e.printStackTrace();
}
return t;
}
public static Object read(String filename, Context context) {
Object t = null;
try {
FileInputStream fis = context.openFileInput(filename);
ObjectInputStream os = new ObjectInputStream(fis);
t = (Object) os.readObject();
os.close();
} catch (Exception e) {
}
return t;
}
void load(Context context, final GameActivity gameActivity) {
Game data;
try {
FileInputStream saveData = context.openFileInput(gameActivity.getDataFile());
ObjectInputStream in = new ObjectInputStream(saveData);
data = (Game) in.readObject();
in.close();
saveData.close();
} catch (Exception e) {
newGame(gameActivity, gameActivity.getPlayerName());
return;
}
npcsGivenTo = new ArrayList<>(data.npcsGivenTo);
npcsSpokenTo = new ArrayList<>(data.npcsSpokenTo);
pointChanges = new ArrayList<>(data.pointChanges);
gradeScores = new int[5];
System.arraycopy(
data.gradeScores, 0, gradeScores, 0, data.gradeScores.length);
friendScores = new int[5];
System.arraycopy(
data.friendScores, 0, friendScores, 0, data.friendScores.length);
examScores = new int[5];
System.arraycopy(
data.examScores, 0, examScores, 0, data.examScores.length);
daysSince = new int[5];
System.arraycopy(
data.daysSince, 0, daysSince, 0, data.daysSince.length);
inventory = new TreeMap<>(new ItemComparator());
for (Item item : data.inventory.keySet()) {
int amount = data.inventory.get(item);
item = Item.getItem(item.getId());
inventory.put(item, amount);
}
progressDataStructure = data.progressDataStructure;
points = data.points;
gradePoints = data.gradePoints;
friendPoints = data.friendPoints;
heistPoints = data.heistPoints;
day = data.day;
time = data.time;
averageGP = data.averageGP;
averageFP = data.averageFP;
money = data.money;
gfIndex = data.gfIndex;
bgmId = data.bgmId;
eventBGM = data.eventBGM;
mapId = data.mapId;
sumGP = data.sumGP;
sumFP = data.sumFP;
player = new Player(gameActivity, data.getPlayer());
tileMap = TileMap.getMap(mapId);
camera = new Camera(player.getX() - (CAMERA_WIDTH / 2),
player.getY() - (CAMERA_HEIGHT / 2));
tileMap.removeNPCCollisions();
tileMap.update();
gameCharacters.clear();
gameCharacters.add(player);
this.destination = null;
addNPCsFromData(gameActivity, data);
gameCharacterMatrix = new GameCharacter[tileMap.getRows()][tileMap.getCols()];
for (GameCharacter gc : gameCharacters) {
gameCharacterMatrix[gc.getY()][gc.getX()] = gc;
tileMap.setCollision(gc.getX(), gc.getY(), 2);
}
rated = data.rated;
camera.setBoundingBox();
bgmId = tileMap.getBGM();
if (eventBGM > -1) { bgm = MediaPlayer.create(gameActivity, eventBGM); }
else { bgm = MediaPlayer.create(gameActivity, bgmId); }
bgm.setLooping(true);
bgm.start();
jingle = MediaPlayer.create(gameActivity, R.raw._jingle_get_item);
}
/**
* Handle a word list: put it in its right place, and update the passed content values.
* @param context the context for opening files.
* @param inputStream an input stream pointing to the downloaded data. May not be null.
* Will be closed upon finishing.
* @param downloadRecord the content values to fill the file name in.
* @throws IOException if files can't be read or written.
* @throws BadFormatException if the md5 checksum doesn't match the metadata.
*/
private static void handleWordList(final Context context,
final InputStream inputStream, final DownloadRecord downloadRecord)
throws IOException, BadFormatException {
// DownloadManager does not have the ability to put the file directly where we want
// it, so we had it download to a temporary place. Now we move it. It will be deleted
// automatically by DownloadManager.
DebugLogUtils.l("Downloaded a new word list :", downloadRecord.mAttributes.getAsString(
MetadataDbHelper.DESCRIPTION_COLUMN), "for", downloadRecord.mClientId);
PrivateLog.log("Downloaded a new word list with description : "
+ downloadRecord.mAttributes.getAsString(MetadataDbHelper.DESCRIPTION_COLUMN)
+ " for " + downloadRecord.mClientId);
final String locale =
downloadRecord.mAttributes.getAsString(MetadataDbHelper.LOCALE_COLUMN);
final String destinationFile = getTempFileName(context, locale);
downloadRecord.mAttributes.put(MetadataDbHelper.LOCAL_FILENAME_COLUMN, destinationFile);
FileOutputStream outputStream = null;
try {
outputStream = context.openFileOutput(destinationFile, Context.MODE_PRIVATE);
copyFile(inputStream, outputStream);
} finally {
inputStream.close();
if (outputStream != null) {
outputStream.close();
}
}
// TODO: Consolidate this MD5 calculation with file copying above.
// We need to reopen the file because the inputstream bytes have been consumed, and there
// is nothing in InputStream to reopen or rewind the stream
FileInputStream copiedFile = null;
final String md5sum;
try {
copiedFile = context.openFileInput(destinationFile);
md5sum = MD5Calculator.checksum(copiedFile);
} finally {
if (copiedFile != null) {
copiedFile.close();
}
}
if (TextUtils.isEmpty(md5sum)) {
return; // We can't compute the checksum anyway, so return and hope for the best
}
if (!md5sum.equals(downloadRecord.mAttributes.getAsString(
MetadataDbHelper.CHECKSUM_COLUMN))) {
context.deleteFile(destinationFile);
throw new BadFormatException("MD5 checksum check failed : \"" + md5sum + "\" <> \""
+ downloadRecord.mAttributes.getAsString(MetadataDbHelper.CHECKSUM_COLUMN)
+ "\"");
}
}
/**
* Handle a word list: put it in its right place, and update the passed content values.
* @param context the context for opening files.
* @param inputStream an input stream pointing to the downloaded data. May not be null.
* Will be closed upon finishing.
* @param downloadRecord the content values to fill the file name in.
* @throws IOException if files can't be read or written.
* @throws BadFormatException if the md5 checksum doesn't match the metadata.
*/
private static void handleWordList(final Context context,
final InputStream inputStream, final DownloadRecord downloadRecord)
throws IOException, BadFormatException {
// DownloadManager does not have the ability to put the file directly where we want
// it, so we had it download to a temporary place. Now we move it. It will be deleted
// automatically by DownloadManager.
DebugLogUtils.l("Downloaded a new word list :", downloadRecord.mAttributes.getAsString(
MetadataDbHelper.DESCRIPTION_COLUMN), "for", downloadRecord.mClientId);
PrivateLog.log("Downloaded a new word list with description : "
+ downloadRecord.mAttributes.getAsString(MetadataDbHelper.DESCRIPTION_COLUMN)
+ " for " + downloadRecord.mClientId);
final String locale =
downloadRecord.mAttributes.getAsString(MetadataDbHelper.LOCALE_COLUMN);
final String destinationFile = getTempFileName(context, locale);
downloadRecord.mAttributes.put(MetadataDbHelper.LOCAL_FILENAME_COLUMN, destinationFile);
FileOutputStream outputStream = null;
try {
outputStream = context.openFileOutput(destinationFile, Context.MODE_PRIVATE);
copyFile(inputStream, outputStream);
} finally {
inputStream.close();
if (outputStream != null) {
outputStream.close();
}
}
// TODO: Consolidate this MD5 calculation with file copying above.
// We need to reopen the file because the inputstream bytes have been consumed, and there
// is nothing in InputStream to reopen or rewind the stream
FileInputStream copiedFile = null;
final String md5sum;
try {
copiedFile = context.openFileInput(destinationFile);
md5sum = MD5Calculator.checksum(copiedFile);
} finally {
if (copiedFile != null) {
copiedFile.close();
}
}
if (TextUtils.isEmpty(md5sum)) {
return; // We can't compute the checksum anyway, so return and hope for the best
}
if (!md5sum.equals(downloadRecord.mAttributes.getAsString(
MetadataDbHelper.CHECKSUM_COLUMN))) {
context.deleteFile(destinationFile);
throw new BadFormatException("MD5 checksum check failed : \"" + md5sum + "\" <> \""
+ downloadRecord.mAttributes.getAsString(MetadataDbHelper.CHECKSUM_COLUMN)
+ "\"");
}
}