/** * The entire purpose of this function is to recover the issues that were in the old version of * the library and then to delete the remaining file when we are done with it. A user should never * need to call this function, this gets automatically run for them in {@link * Api#init(android.app.Application)}. */ public void recoverOldIssues() { Log.d(TAG, "Attempting to recover old feeback for the benefit of the user."); FileInputStream oldCacheFile = null; try { // Load the old data from a file oldCacheFile = context.openFileInput(OLD_ISSUES_CACHE_FILE); final String oldIssuesWithCommentsJSON = IOUtils.toString(oldCacheFile); // Parse the Data - The old json save contained IssuesWithComments final IssuesWithComments oldIssues = new IssueParser(TAG).parseIssues(oldIssuesWithCommentsJSON); // Save the data in the new database. for (Issue issue : oldIssues.issues()) { addCreatedIssue(issue); } } catch (FileNotFoundException e) { Log.i( TAG, "There was no old version of the issues cache lying around. Don't need to recover anything."); } catch (IOException e) { Log.i(TAG, "Encountered problems handling the old cache file", e); } finally { if (oldCacheFile != null) { try { oldCacheFile.close(); oldCacheFile = null; } catch (IOException e) { Log.wtf(TAG, "Could not close a file that we already had opened.", e); } // Remove the file now that we are done with it. context.deleteFile(OLD_ISSUES_CACHE_FILE); } } }
public void loadGameInfo() throws IOException, JSONException { mGameInfoList.clear(); BufferedReader reader = null; try { InputStream inputStream = mContext.openFileInput(mInfoFileName); reader = new BufferedReader(new InputStreamReader(inputStream)); StringBuilder jsonString = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { jsonString.append(line); } JSONArray array = (JSONArray) new JSONTokener(jsonString.toString()).nextValue(); for (int i = 0; i < array.length(); i++) { JSONObject jsonObject = array.getJSONObject(i); mGameInfoList.add(new GameInfo(jsonObject)); } } catch (FileNotFoundException e) { e.printStackTrace(); } finally { if (reader != null) { reader.close(); } } }
// This function is used to load the list of selected media from internal storage // This should only be called from AlarmixActivity public void loadSelectedMedia(Context context) { try { FileInputStream is = context.openFileInput(FILE_NAME_SELECTED_MEDIA); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); // read form the stream to build the media list ArrayList<String> lstMedia = new ArrayList<String>(); String line; while ((line = br.readLine()) != null) { if (!line.isEmpty()) lstMedia.add(new String(line)); } m_model.lstMediaPaths = lstMedia; // clean up br.close(); isr.close(); is.close(); } catch (FileNotFoundException e) { // maybe the file hasn't been created yet // in that case, leave model.lstMediaPaths as an empty list e.printStackTrace(); } catch (IOException e) { // something went wrong when reading from file? e.printStackTrace(); } }
// This function is used to load the list of selected media from internal storage // This should only be called from AlarmixActivity public void loadGlobalId(Context context) { try { m_model.gId = 0; FileInputStream is = context.openFileInput(FILE_NAME_GLOBAL_ID); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); // read form the stream to build the media list String line; if ((line = br.readLine()) != null) { if (!line.isEmpty()) m_model.gId = Integer.parseInt(line); } // clean up br.close(); isr.close(); is.close(); } catch (NumberFormatException e) { // the number you are parsing is wrong? check saveGlobalId just in case e.printStackTrace(); } catch (FileNotFoundException e) { // maybe the file hasn't been created yet // in that case, leave model.lstMediaPaths as an empty list e.printStackTrace(); } catch (IOException e) { // something went wrong when reading from file? e.printStackTrace(); } }
public RSSFeed readFile() { try { // get the XML reader SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser parser = factory.newSAXParser(); XMLReader xmlreader = parser.getXMLReader(); // set content handler RSSFeedHandler theRssHandler = new RSSFeedHandler(); xmlreader.setContentHandler(theRssHandler); // read the file from internal storage FileInputStream in = context.openFileInput(FILENAME); // parse the data InputSource is = new InputSource(in); xmlreader.parse(is); // set the feed in the activity RSSFeed feed = theRssHandler.getFeed(); return feed; } catch (Exception e) { Log.e("News reader", e.toString()); return null; } }
public List<Crime> loadCrimes() throws IOException, JSONException { List<Crime> crimes = new ArrayList<>(); BufferedReader reader = null; try { InputStream in = context.openFileInput(fileName); reader = new BufferedReader(new InputStreamReader(in)); StringBuilder jsonString = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { jsonString.append(line); } JSONArray array = (JSONArray) new JSONTokener(jsonString.toString()).nextValue(); for (int i = 0; i < array.length(); i++) { crimes.add(new Crime(array.getJSONObject(i))); } } catch (FileNotFoundException ignored) { } finally { if (reader != null) { reader.close(); } } return crimes; }
public static Object readObjectFile(Context context, String filename, Boolean external) { Object content = new Object(); try { File file; FileInputStream fin; if (external) { file = new File(context.getExternalFilesDir(null), filename); fin = new FileInputStream(file); } else { file = new File(filename); fin = context.openFileInput(filename); } ObjectInputStream ois = new ObjectInputStream(fin); try { content = (Object) ois.readObject(); } catch (ClassNotFoundException e) { Log.e("READ ERROR", "INVALID JAVA OBJECT FILE"); } ois.close(); fin.close(); } catch (FileNotFoundException e) { Log.e("READ ERROR", "FILE NOT FOUND " + filename); return null; } catch (IOException e) { Log.e("READ ERROR", "I/O ERROR"); } return content; }
/** 游戏数据读取 */ public static int[] loadData(Context context) { FileInputStream fis = null; int[] datas = {-1, Const.TOTAL_COIN}; try { fis = context.openFileInput(Const.FILE_NAME_SAVE_DATA); DataInputStream dis = new DataInputStream(fis); try { datas[Const.INDEX_LOAD_DATA_STAGE] = dis.readInt(); } catch (IOException e) { e.printStackTrace(); } try { datas[Const.INDEX_LOAD_DATA_COIN] = dis.readInt(); } catch (IOException e) { e.printStackTrace(); } } catch (FileNotFoundException e) { e.printStackTrace(); } finally { if (fis != null) { try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } } return datas; }
public static String readStringFile(Context context, String filename, Boolean external) { String content = ""; try { File file; FileInputStream fin; if (external) { file = new File(context.getExternalFilesDir(null), filename); fin = new FileInputStream(file); } else { file = new File(filename); fin = context.openFileInput(filename); } BufferedInputStream bin = new BufferedInputStream(fin); byte[] contentBytes = new byte[1024]; int bytesRead = 0; StringBuffer contentBuffer = new StringBuffer(); while ((bytesRead = bin.read(contentBytes)) != -1) { content = new String(contentBytes, 0, bytesRead); contentBuffer.append(content); } content = contentBuffer.toString(); fin.close(); } catch (FileNotFoundException e) { Log.e("READ ERROR", "FILE NOT FOUND " + filename); } catch (IOException e) { Log.e("READ ERROR", "I/O ERROR"); } return content; }
public ArrayList<Offer> loadOffers() throws IOException, JSONException { ArrayList<Offer> offers = new ArrayList<Offer>(); BufferedReader reader = null; try { // �������� � ������ ����� � StringBuilder InputStream in = mContext.openFileInput(mFilename); reader = new BufferedReader(new InputStreamReader(in)); StringBuilder jsonString = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { // Line breaks are omitted and irrelevant jsonString.append(line); } // ������ JSON � �������������� JSONTokener JSONArray array = (JSONArray) new JSONTokener(jsonString.toString()).nextValue(); for (int i = 0; i < array.length(); i++) { offers.add(new Offer(array.getJSONObject(i))); } } catch (FileNotFoundException e) { // ���������� ��� ������ "� ����"; �� ��������� �������� } finally { if (reader != null) reader.close(); } return offers; }
public BufferedReader getReader() { String storageMode = getStorageMode(); String synchMode = getSynchMode(); BufferedReader reader = null; try { if (storageMode.equals("sdcard") || synchMode.equals("sdcard")) { File root = Environment.getExternalStorageDirectory(); File morgDir = new File(root, "mobileorg"); File morgFile = new File(morgDir, fileName); if (!morgFile.exists()) { return null; } FileReader freader = new FileReader(morgFile); reader = new BufferedReader(freader); } else if (storageMode.equals("internal") || storageMode.equals("")) { String dirActual = this.fileName; FileInputStream fs; fs = context.openFileInput(dirActual); reader = new BufferedReader(new InputStreamReader(fs)); } } catch (FileNotFoundException e) { return null; } return reader; }
public void loadGameState() throws IOException, JSONException { BufferedReader reader = null; JSONArray jsonStateArray = null; try { InputStream inputStream = mContext.openFileInput(GameConfig.GAME_STATE_FILE_NAME); reader = new BufferedReader(new InputStreamReader(inputStream)); StringBuilder jsonString = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { jsonString.append(line); } jsonStateArray = (JSONArray) new JSONTokener(jsonString.toString()).nextValue(); JSONObject scoreObject = jsonStateArray.getJSONObject(0); JSONObject panelObject = jsonStateArray.getJSONObject(1); mScore = scoreObject.getInt(JSON_SCORE); int pos = 0; for (int i = 0; i < GameConfig.SQUARE_COUNT; i++) { for (int j = 0; j < GameConfig.SQUARE_COUNT; j++) { mGamePanel[i][j] = panelObject.getInt(JSON_GAME_POS_NUM + pos); pos++; } } } catch (FileNotFoundException e) { e.printStackTrace(); } finally { if (reader != null) { reader.close(); } } }
public Object readObject(String location) { try { Log.d("UseInternalStorage", location); FileInputStream fis = rootActivity.openFileInput(location); ObjectInputStream is = new ObjectInputStream(fis); Object ob = is.readObject(); is.close(); Log.d(TAG, "odczytano polik " + location); return ob; } catch (StreamCorruptedException e) { e.printStackTrace(); return null; } catch (IOException e) { e.printStackTrace(); return null; } catch (ClassNotFoundException e) { e.printStackTrace(); return null; } catch (NullPointerException e) { e.printStackTrace(); return null; } }
/** * Loads key store from storage, or creates new one if storage is missing key store or corrupted. */ private KeyStore load() { KeyStore keyStore; try { keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); } catch (KeyStoreException e) { throw new IllegalStateException("Unable to get default instance of KeyStore", e); } try { FileInputStream fis = mContext.openFileInput(KEYSTORE_FILENAME); keyStore.load(fis, KEYSTORE_PASSWORD); } catch (IOException e) { LogUtils.v("Unable open keystore file", e); keyStore = null; } catch (GeneralSecurityException e) { LogUtils.v("Unable open keystore file", e); keyStore = null; } if (keyStore != null) { // KeyStore loaded return keyStore; } try { keyStore = createKeyStore(); } catch (GeneralSecurityException e) { throw new IllegalStateException("Unable to create identity KeyStore", e); } store(keyStore); return keyStore; }
public ArrayList<Note> loadNotes() throws IOException, JSONException { ArrayList<Note> notes = new ArrayList<Note>(); BufferedReader reader = null; try { // Open and read the file into a StringBuilder InputStream in = mContext.openFileInput(mFilename); reader = new BufferedReader(new InputStreamReader(in)); StringBuilder jsonString = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { jsonString.append(line); } // Parse the JSON using JSONTokener JSONArray array = (JSONArray) new JSONTokener(jsonString.toString()).nextValue(); // Build the array of notes from JSONObjects for (int i = 0; i < array.length(); ++i) { notes.add(new Note(array.getJSONObject(i))); } } catch (FileNotFoundException e) { // Ignore, happens when starting fresh } finally { if (reader != null) { reader.close(); } } return notes; }
public static Object readObject(Context context, String key) throws IOException, ClassNotFoundException { FileInputStream fis = context.openFileInput(key); ObjectInputStream ois = new ObjectInputStream(fis); Object object = ois.readObject(); return object; }
private GeotriggerConfig readFromInternalStorage() { Log.v(Config.TAG, "read from internal storage"); GeotriggerConfig config = null; try { File file = mContext.getFileStreamPath(CONFIG_FILE); if (file.exists() == true) { Log.v(Config.TAG, "readFileFromInternalStorage File found..."); FileInputStream fis = mContext.openFileInput(file.getName()); StringBuilder buffer = new StringBuilder(); int ch; while ((ch = fis.read()) != -1) { buffer.append((char) ch); } Log.v(Config.TAG, "readFileFromInternalStorage complete.. " + buffer.toString()); fis.close(); config = new GeotriggerConfig(buffer.toString()); } } catch (Exception e) { Log.v(Config.TAG, "Error: " + e.getMessage()); } return config; }
/** * retrieve the auth token string securely * * @param context Context used to read storage * @return String of the stored access token, returns "" if no access token exists. */ public static String getAccessToken(Context context) { String accessToken = ""; String filename = getAccessTokenFilename(context.getApplicationContext()); File authFile = context.getDir(filename, Context.MODE_PRIVATE); try { if (!authFile.exists()) { Log.e( AppBlade.LogTag, "Trying to create Authfile location : " + authFile.getAbsolutePath()); authFile.mkdirs(); authFile.createNewFile(); } FileInputStream fis = context.openFileInput(filename); InputStreamReader inputStreamReader = new InputStreamReader(fis); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); accessToken = bufferedReader.readLine(); } catch (Exception ex) { Log.w(AppBlade.LogTag, "Error creating Access Token ", ex); } if (!authFile.exists()) { Log.e(AppBlade.LogTag, "Did not create Authfile location : " + authFile); } Log.v( AppBlade.LogTag, String.format("getAccessToken File:%s, token:%s", filename, accessToken)); return accessToken; }
private String readHistoryFileAsString() { Reader reader = null; try { reader = new InputStreamReader(context.openFileInput(HISTORY_FILE_NAME), HISTORY_FILE_ENCODING); StringBuilder sb = new StringBuilder(); char[] buffer = new char[1024]; for (; ; ) { int size = reader.read(buffer); if (size < 0) { break; } sb.append(buffer, 0, size); } return sb.toString(); } catch (FileNotFoundException e) { Log.i(TAG, "history file not found, use empty"); } catch (IOException e) { Log.e(TAG, "open history file fail", e); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { } } } return null; }
// 从JSON文件中读取JSON数据,并转换为JSONObject类型的string,然后解析为JSONArray,再解析为ArrayList并返回ArrayList public ArrayList<Crime> loadCrimes() throws IOException, JSONException { ArrayList<Crime> crimes = new ArrayList<Crime>(); BufferedReader reader = null; try { InputStream in = mContext.openFileInput(mFilename); reader = new BufferedReader(new InputStreamReader(in)); StringBuilder jsonString = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { jsonString.append(line); } // 将JSONObject类型的string解析为json数组 JSONArray array = (JSONArray) new JSONTokener(jsonString.toString()).nextValue(); for (int i = 0; i < array.length(); i++) { crimes.add(new Crime(array.getJSONObject(i))); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (reader != null) { reader.close(); } } return crimes; }
public ArrayList<NixMashupLink> loadLinks() throws IOException, JSONException { ArrayList<NixMashupLink> crimes = new ArrayList<NixMashupLink>(); BufferedReader reader = null; try { // open and read the file into a StringBuilder InputStream in = mContext.openFileInput(mFilename); reader = new BufferedReader(new InputStreamReader(in)); StringBuilder jsonString = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { // line breaks are omitted and irrelevant jsonString.append(line); } // parse the JSON using JSONTokener JSONArray array = (JSONArray) new JSONTokener(jsonString.toString()).nextValue(); // build the array of crimes from JSONObjects for (int i = 0; i < array.length(); i++) { crimes.add(new NixMashupLink(array.getJSONObject(i))); } } catch (FileNotFoundException e) { // we will ignore this one, since it happens when we start fresh } finally { if (reader != null) reader.close(); } return crimes; }
/** * 读取对象 * * @param file * @return */ public Serializable readObject(Context ctx, String file) { if (!isExistDataCache(ctx, file)) return null; FileInputStream fis = null; ObjectInputStream ois = null; try { fis = ctx.openFileInput(file); ois = new ObjectInputStream(fis); return (Serializable) ois.readObject(); } catch (FileNotFoundException e) { } catch (Exception e) { e.printStackTrace(); // 反序列化失败 - 删除缓存文件 if (e instanceof InvalidClassException) { File data = ctx.getFileStreamPath(file); data.delete(); } } finally { try { ois.close(); } catch (Exception e) { } try { fis.close(); } catch (Exception e) { } } return null; }
public List<HistoryItem> loadAll() { if (!ctx.getFileStreamPath(HISTORY_FILENAME).exists()) { return null; } ObjectInputStream in = null; try { in = new ObjectInputStream(ctx.openFileInput(HISTORY_FILENAME)); @SuppressWarnings("unchecked") // readObject() return Object. List<HistoryItem> res = (List<HistoryItem>) in.readObject(); return res; } catch (Exception e) { Log.e(TAG, "Unable to deserialize history", e); // delete it as it's likely corrupted ctx.getFileStreamPath(HISTORY_FILENAME).delete(); return null; } finally { if (in != null) { try { in.close(); } catch (IOException e) { Log.e(TAG, "", e); } } } }
public void load() { try { InputStream is = new BufferedInputStream(mContext.openFileInput(FILE_NAME), 8192); DataInputStream in = new DataInputStream(is); int version = in.readInt(); if (version > LAST_VERSION) { throw new IOException("data version " + version + "; expected " + LAST_VERSION); } if (version > 1) { mDeleteMode = in.readInt(); } if (version > 2) { int quickSerializable = in.readInt(); for (Base m : Base.values()) { if (m.getQuickSerializable() == quickSerializable) this.mMode = m; } } mHistory = new History(version, in); in.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
public String readFromFile() { String ret = ""; try { InputStream inputStream = context.openFileInput("locations.json"); 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(); ret = stringBuilder.toString(); } } catch (FileNotFoundException ex) { Log.e("login activity", "File not found: " + ex.toString()); } catch (IOException ex) { Log.e("login activity", "Can not read file: " + ex.toString()); } return ret; }
/* * Chargement des informations du reveil. * Ici pour la sauvegarde on a simplement déserialiser l'objet Alarm. */ public void charger() { alarm = null; try { ObjectInputStream alarmOIS = new ObjectInputStream(context.openFileInput("alarm.serial")); try { alarm = (Alarm) alarmOIS.readObject(); } finally { try { alarmOIS.close(); } finally {; } } } catch (FileNotFoundException fnfe) { alarm = new Alarm(); alarm.setActive(true); Time t = new Time(); t.hour = 7; t.minute = 30; alarm.setHeure(t); } catch (IOException ioe) { ioe.printStackTrace(); } catch (ClassNotFoundException cnfe) { cnfe.printStackTrace(); } }
@Override public void onReceive(Context context, Intent intent) { SharedPreferences sharedPrefs = context.getSharedPreferences(PREFS_NAME, 0); mSmsDisabled = sharedPrefs.getBoolean(PREFS_IS_SMS_BLOCKED, false); if (mSmsDisabled) { // Prevent other apps from receiving the SMS abortBroadcast(); List<SmsDataCache> currBlockedMsgs = new ArrayList<SmsDataCache>(); // Check if file exists with our cached messages if (context.getFileStreamPath(SMS_FILENAME).exists()) { // Build array of currently blocked messages from app's private file try { FileInputStream fis = context.openFileInput(SMS_FILENAME); ObjectInputStream ois = new ObjectInputStream(fis); try { // Read messages and updated currBlockedMsgs array. ArrayList<SmsDataCache> cachedMsgs = (ArrayList<SmsDataCache>) ois.readObject(); for (Iterator<SmsDataCache> iter = cachedMsgs.iterator(); iter.hasNext(); ) { SmsDataCache cachedMsg = iter.next(); currBlockedMsgs.add(cachedMsg); } } catch (Exception e) { e.printStackTrace(); } ois.close(); fis.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } // Update private file with the message that was just received try { // Update array of blocked messages with the last received message SmsDataCache receivedMsg = new SmsDataCache(intent); currBlockedMsgs.add(receivedMsg); FileOutputStream fos = context.openFileOutput(SMS_FILENAME, Context.MODE_PRIVATE); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(currBlockedMsgs); oos.flush(); oos.close(); fos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
@Override protected InputStream openRead(String path, boolean error) throws IOException { if (error) { return context.getAssets().open(path); } else { return context.openFileInput(path); } }
/** * Read file from the internal storage dedicated for application space.<br> * <br> * <b>Important:</b>The file you read had to be saved before, by using: {@link * InternalStorage#createFile(String, String)} * * @param name * @return */ public byte[] readFile(String name) { try { FileInputStream stream = mContext.openFileInput(name); byte[] out = readFile(stream); return out; } catch (IOException e) { throw new RuntimeException("Failed to create private file on internal storage", e); } }
/** * 读取文本文件 * * @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 ""; }