Java Code Examples for android.content.Context#openFileInput()

The following examples show how to use android.content.Context#openFileInput() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ProfileManager.java    From Cake-VPN with GNU General Public License v2.0 6 votes vote down vote up
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);
        }
    }
}
 
Example 2
Source File: DataProvider.java    From callmeter with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 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();
}
 
Example 3
Source File: ProfileManager.java    From SimpleOpenVpn-Android with Apache License 2.0 6 votes vote down vote up
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);
        }
    }
}
 
Example 4
Source File: ProfileManager.java    From android with GNU General Public License v3.0 6 votes vote down vote up
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);
        }
    }
}
 
Example 5
Source File: PinnedBlockedApps.java    From Taskbar with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 6
Source File: FileUtils.java    From IdealMedia with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 7
Source File: ProtoUtilsTest.java    From PainlessMusicPlayer with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 8
Source File: FileUtils.java    From freemp with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 9
Source File: FileUtils.java    From MissZzzReader with Apache License 2.0 5 votes vote down vote up
/**
 * 读取文本文件
 * 
 * @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 "";
}
 
Example 10
Source File: ZenPostModel.java    From zen4android with MIT License 5 votes vote down vote up
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;
}
 
Example 11
Source File: FileUtil.java    From FriendBook with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 读取文本文件
 *
 * @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 "";
}
 
Example 12
Source File: FileUtils.java    From Varis-Android with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example 13
Source File: LoadImageUtil.java    From natrium-android-wallet with BSD 2-Clause "Simplified" License 5 votes vote down vote up
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;
}
 
Example 14
Source File: PushjetService.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public boolean iconCached(Context context) {
    if (!hasIcon())
        return false;
    try {
        context.openFileInput(MiscUtil.iconFilename(this.icon));
        return true;
    } catch (IOException ignore) {
        return false;
    }
}
 
Example 15
Source File: PushfishService.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public boolean iconCached(Context context) {
    if (!hasIcon())
        return false;
    try {
        context.openFileInput(MiscUtil.iconFilename(this.icon));
        return true;
    } catch (IOException ignore) {
        return false;
    }
}
 
Example 16
Source File: FileUtils.java    From android-tv-launcher with MIT License 5 votes vote down vote up
/**
 * 读取文本文件
 * 
 * @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 "";
	}

}
 
Example 17
Source File: AppEventsLogger.java    From facebook-api-android-maven with Apache License 2.0 5 votes vote down vote up
@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;
            }
        }
    }
}
 
Example 18
Source File: UpdateHandler.java    From AOSP-Kayboard-7.1.2 with Apache License 2.0 4 votes vote down vote up
/**
 * 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)
                + "\"");
    }
}
 
Example 19
Source File: UpdateHandler.java    From Indic-Keyboard with Apache License 2.0 4 votes vote down vote up
/**
 * 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)
                + "\"");
    }
}
 
Example 20
Source File: Game.java    From SchoolQuest with GNU General Public License v3.0 4 votes vote down vote up
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);
}