public static String saveBitmapToLocalFile(Context context, String fileName, Bitmap image) { try { if (fileName == null) throw new Exception("No filename."); if (image == null) throw new Exception("No image."); String absolutePath = getAbsolutePath(context, fileName); ByteArrayOutputStream bs = new ByteArrayOutputStream(); image.compress(Bitmap.CompressFormat.PNG, 0, bs); FileOutputStream outputStream = context.openFileOutput( fileName, Context.MODE_WORLD_READABLE | Context.MODE_WORLD_WRITEABLE); if (outputStream != null) { outputStream.write(bs.toByteArray()); } else { throw new Exception("Unable to open output file stream."); } return absolutePath; } catch (Exception e) { e.printStackTrace(); return null; } }
public static void writeObject(Context context, String key, Object object) throws IOException { FileOutputStream fos = context.openFileOutput(key, Context.MODE_PRIVATE); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(object); oos.close(); fos.close(); }
public boolean writeObject(Object ob, String location) { try { FileOutputStream fos = rootActivity.openFileOutput(location, Context.MODE_PRIVATE); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(ob); oos.close(); Log.d(TAG, "zaposano polik " + location); } catch (FileNotFoundException e) { e.printStackTrace(); return false; } catch (IOException e) { e.printStackTrace(); return false; } catch (NullPointerException e) { e.printStackTrace(); return false; } catch (Exception e) { e.printStackTrace(); return false; } return true; }
public void downloadFile() { try { // get the URL URL url = new URL(URL_STRING); // get the input stream InputStream in = url.openStream(); context.deleteFile(FILENAME); // get the output stream FileOutputStream out = context.openFileOutput(FILENAME, Context.MODE_PRIVATE); // read input and write output byte[] buffer = new byte[1024]; int bytesRead = in.read(buffer); while (bytesRead != -1) { out.write(buffer, 0, bytesRead); bytesRead = in.read(buffer); } out.close(); in.close(); } catch (IOException e) { Log.e("News reader", e.toString()); } }
/** 游戏数据保存 */ public static void saveData(Context context, int stageIndex, int coins) { FileOutputStream fis = null; try { fis = context.openFileOutput(Const.FILE_NAME_SAVE_DATA, Context.MODE_PRIVATE); // 文件输出 DataOutputStream dos = new DataOutputStream(fis); // 管道流 try { dos.writeInt(stageIndex); // 写入关卡数据 } catch (IOException e) { e.printStackTrace(); } try { dos.writeInt(coins); // 写入金币 } catch (IOException e) { e.printStackTrace(); } } catch (FileNotFoundException e) { e.printStackTrace(); } finally { // 关闭文件流 if (fis != null) { try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } } }
private void openIfRequired() throws IOException { String state = Environment.getExternalStorageState(); if (mSerializer == null) { String fileName = mReportFile; if (mMultiFile) { fileName = fileName.replace("$(suite)", "test"); } if (mReportDir == null) { if (Environment.MEDIA_MOUNTED.equals(state) && !Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { File f = mContext.getExternalFilesDir("testng"); mOutputStream = new FileOutputStream(new File(f, fileName)); } else { mOutputStream = mTargetContext.openFileOutput(fileName, 0); } } else { mOutputStream = new FileOutputStream(new File(mReportDir, fileName)); } mSerializer = Xml.newSerializer(); mSerializer.setOutput(mOutputStream, ENCODING_UTF_8); mSerializer.startDocument(ENCODING_UTF_8, true); if (!mMultiFile) { mSerializer.startTag("", TAG_SUITES); } } }
public void saveTicket() { Log.d("GenTicket", "saveTicket...ok(1)"); FileOutputStream outputStream; File file = new File(context.getFilesDir(), filename); Log.d("saveTicket", "path:" + file.getAbsolutePath()); String newuser = currentUser + "\n"; try { outputStream = context.openFileOutput(filename, Context.MODE_PRIVATE); outputStream.write(newuser.getBytes()); Log.d("saving", "user:"******"saving", "ticket:" + currentTicket); outputStream.write(currentTicket.getBytes()); outputStream.close(); } catch (Exception e) { Toast toast = Toast.makeText( context, "Ocurrio el siguiente error al escribir un archivo:" + e.getMessage(), Toast.LENGTH_LONG); toast.show(); } Log.d("GenTicket", "saveTicket...ok(2)"); }
// This function is used to save the list of selected media to internal storage public void saveSelectedMedia(Context context, ArrayList<String> lstMedia) { m_model.lstMediaPaths = lstMedia; try { FileOutputStream os = context.openFileOutput(FILE_NAME_SELECTED_MEDIA, MODE_PRIVATE); // build the string which will be written to this stream String strOutput = new String(); for (String filePath : lstMedia) { if (!strOutput.isEmpty()) { strOutput += LIST_DELIMITER; } strOutput += filePath; } // write to the output stream os.write(strOutput.getBytes()); // clean up os.close(); } catch (FileNotFoundException e) { // please make sure you are calling this by passing in an Activity context... e.printStackTrace(); } catch (IOException e) { // something went wrong when writing to file? e.printStackTrace(); } }
@Override protected String doInBackground(String... aurl) { int count; try { URL url = new URL(aurl[0]); URLConnection conexion = url.openConnection(); conexion.connect(); int lenghtOfFile = conexion.getContentLength(); InputStream input = new BufferedInputStream(url.openStream()); output = fileContext.openFileOutput("d.jpg", Context.MODE_PRIVATE); byte data[] = new byte[1024]; long total = 0; while ((count = input.read(data)) != -1) { total += count; publishProgress("" + (int) ((total * 100) / lenghtOfFile)); output.write(data, 0, count); } output.flush(); output.close(); input.close(); } catch (Exception e) { } return null; }
public static void takeNotes(String message) { FileOutputStream fos = null; try { fos = mContext.openFileOutput(getLogFileName(), Context.MODE_APPEND); String msg = "\n\n"; msg += android.text.format.DateFormat.format("yyyy-MM-dd kk:mm:ss", System.currentTimeMillis()); msg += "===================================================="; msg += "\n\n"; msg += message; byte[] buffer = msg.getBytes(); fos.write(buffer); } catch (IOException e1) { e1.printStackTrace(); } finally { if (fos != null) { try { fos.close(); } catch (IOException e1) { e1.printStackTrace(); } fos = null; } } }
// 添加一条记录 public static void addFile(String title, String content, Context context) { FileOutputStream fout = null; OutputStreamWriter writer = null; PrintWriter pw = null; try { fout = context.openFileOutput(title, context.MODE_PRIVATE); writer = new OutputStreamWriter(fout); pw = new PrintWriter(writer); pw.print(content); pw.flush(); } catch (FileNotFoundException e) { e.printStackTrace(); } finally { if (pw != null) { pw.close(); } if (writer != null) { try { writer.close(); } catch (IOException e) { e.printStackTrace(); } } if (fout != null) { try { fout.close(); } catch (IOException e) { e.printStackTrace(); } } } }
public static void get_assetsScript(String fn, Context c, String prefix, String postfix) { byte[] buffer; final AssetManager assetManager = c.getAssets(); try { InputStream f = assetManager.open(fn); buffer = new byte[f.available()]; f.read(buffer); f.close(); final String s = new String(buffer); final StringBuffer sb = new StringBuffer(s); if (!postfix.equals("")) { sb.append("\n\n" + postfix); } if (!prefix.equals("")) { sb.insert(0, prefix + "\n"); } sb.insert(0, "#!" + Helpers.binExist("sh") + "\n\n"); try { FileOutputStream fos; fos = c.openFileOutput(fn, Context.MODE_PRIVATE); fos.write(sb.toString().getBytes()); fos.close(); } catch (IOException e) { Log.d(TAG, "error write " + fn + " file"); e.printStackTrace(); } } catch (IOException e) { Log.d(TAG, "error read " + fn + " file"); e.printStackTrace(); } }
private String saveCrashInfoToFile(Throwable ex) { Writer info = new StringWriter(); PrintWriter printWriter = new PrintWriter(info); ex.printStackTrace(printWriter); Throwable cause = ex.getCause(); while (cause != null) { cause.printStackTrace(printWriter); cause = cause.getCause(); } String result = info.toString(); printWriter.close(); mDeviceCrashInfo.put(STACK_TRACE, result); try { long timestamp = System.currentTimeMillis(); String fileName = "crash-" + timestamp + CRASH_REPORTER_EXTENSION; FileOutputStream trace = mContext.openFileOutput(fileName, Context.MODE_PRIVATE); mDeviceCrashInfo.store(trace, ""); trace.flush(); trace.close(); return fileName; } catch (Exception e) { if (Constant.DEBUG) { e.printStackTrace(); } // Log.e(TAG, "an error occured while writing report file...", e); } return null; }
private static void addMessageToCache(Context paramContext, String paramString1, String paramString2) { try { paramString1 = paramString1 + ":" + paramString2 + "\001"; Log.i("Texting Component", "Caching " + paramString1); paramContext = paramContext.openFileOutput("textingmsgcache", 32768); paramContext.write(paramString1.getBytes()); paramContext.close(); messagesCached += 1; Log.i("Texting Component", "Cached " + paramString1); return; } catch (FileNotFoundException paramContext) { Log.e("Texting Component", "File not found error writing to cache file"); paramContext.printStackTrace(); return; } catch (IOException paramContext) { Log.e("Texting Component", "I/O Error writing to cache file"); paramContext.printStackTrace(); } }
public void saveGameState(int score, int[][] gamePanel) throws IOException { mScore = score; JSONArray jsonStateArray = new JSONArray(); BufferedWriter writer = null; try { JSONObject scoreObject = new JSONObject(); scoreObject.put(JSON_SCORE, mScore); jsonStateArray.put(scoreObject); JSONObject panelObject = new JSONObject(); int pos = 0; for (int i = 0; i < GameConfig.SQUARE_COUNT; i++) { for (int j = 0; j < GameConfig.SQUARE_COUNT; j++) { panelObject.put(JSON_GAME_POS_NUM + pos, gamePanel[i][j]); pos++; } } jsonStateArray.put(panelObject); OutputStream outputStream = mContext.openFileOutput(GameConfig.GAME_STATE_FILE_NAME, Context.MODE_PRIVATE); writer = new BufferedWriter(new OutputStreamWriter(outputStream)); writer.write(jsonStateArray.toString()); } catch (Exception e) { e.printStackTrace(); } finally { if (writer != null) { writer.close(); } } }
public static boolean CopyResourceToStorage(int resourceId, String path, boolean force) { File file = new File(path); // 파일이 존재하면 true return if (file.exists() && !force) { return true; } InputStream inputStream = null; OutputStream outputStream = null; try { // Stream 복사 inputStream = context.getResources().openRawResource(resourceId); outputStream = context.openFileOutput(path, Context.MODE_PRIVATE); IOUtils.copy(inputStream, outputStream); } catch (Exception e) { path = e.getMessage(); return false; } finally { IOUtils.closeQuietly(inputStream); IOUtils.closeQuietly(outputStream); } return true; }
public static void setBitmapToFile(String cachePath, String imageName, Bitmap bitmap) { File file = null; FileOutputStream fos = null; try { file = new File(cachePath, imageName); if (!file.exists()) { File file2 = new File(cachePath); file2.mkdirs(); } if (Utils.hasSDCard()) { fos = new FileOutputStream(file); } else { fos = context.openFileOutput(imageName, Context.MODE_PRIVATE); } bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos); fos.flush(); } catch (Exception e) { e.printStackTrace(); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { e.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(); } } }
public static void WriteSettings(Context context, String data, String file) throws IOException { FileOutputStream fos = null; OutputStreamWriter osw = null; fos = context.openFileOutput(file, Context.MODE_PRIVATE); osw = new OutputStreamWriter(fos); osw.write(data); osw.close(); fos.close(); }
/** Open file output stream */ private FileOutputStream getOutStream(Date date) { FileOutputStream outStream = null; try { outStream = mContext.openFileOutput(getLogFileName(date), Context.MODE_APPEND); } catch (FileNotFoundException e) { Log.e(LOGTAG, Log.getStackTraceString(e)); } return outStream; }
public static boolean write(Context context, String fileName, String string, String charset) { boolean result = true; try { OutputStream output = context.openFileOutput(fileName, Context.MODE_PRIVATE); result = write(output, string, charset); } catch (FileNotFoundException e) { } return result; }
/** * It store the filedata into the file given by the filename * * @param context the activity context * @param filename the filename to store in * @param filedata the string to be stored */ public static void offlineDataWriter(Context context, String filename, String filedata) { try { FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE); fos.write(filedata.getBytes()); fos.close(); } catch (Exception e) { Log.e(Functions.class.getSimpleName(), e.getMessage(), e); } }
public void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == Activity.RESULT_OK) { if (requestCode == SELECT_IMAGE || requestCode == SELECT_LANDSCAPE_IMAGE) { Bitmap photo = null; String key = null; String filename = null; // code for receiving the cropped image /*Bundle extras = data.getExtras(); if (extras != null) { photo = extras.getParcelable("data"); }*/ InputStream stream; try { stream = getContentResolver().openInputStream(data.getData()); photo = BitmapFactory.decodeStream(stream); stream.close(); } catch (FileNotFoundException e1) { // problems } catch (IOException e) { // problems } if (requestCode == SELECT_IMAGE) { key = MainActivity.isBgSet; filename = selectImagePref.filename; } else if (requestCode == SELECT_LANDSCAPE_IMAGE) { key = MainActivity.isLandscapeSet; filename = selectLandscapeImagePref.filename; } try { if (MainActivity.DEBUGGABLE) { Toast.makeText(Preferences.this, filename, Toast.LENGTH_LONG).show(); } FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE); photo.compress(Bitmap.CompressFormat.PNG, 100, fos); fos.close(); } catch (Exception e) { // shit happens } if (MainActivity.DEBUGGABLE) { // Toast.makeText(Preferences.this, filename, // Toast.LENGTH_LONG).show(); } settings.edit().putBoolean(key, false).commit(); settings.edit().putBoolean(key, true).commit(); if (MainActivity.DEBUGGABLE) { // Toast.makeText(Preferences.this, "" + // settings.getBoolean(key, false), // Toast.LENGTH_LONG).show(); } if (requestCode == SELECT_IMAGE) { selectImagePref.updateBackgroundImage(null); } else if (requestCode == SELECT_LANDSCAPE_IMAGE) { selectLandscapeImagePref.updateBackgroundImage(null); } } } }
public void onReceive(Context context, Intent intent) { // Retrieves a map of extended data from the intent. final Bundle bundle = intent.getExtras(); temp = intent.getAction(); Log.i("Receiver", "Broadcast received: " + temp); data = intent.getExtras().getString("data"); if (data != null) { try { FileOutputStream fOut = context.openFileOutput("test", Context.MODE_PRIVATE); fOut.write(data.getBytes()); fOut.close(); Log.i("WRITE", "done" + data); } catch (IOException e) { e.printStackTrace(); } } try { FileInputStream fin = context.openFileInput("test"); InputStreamReader inputStreamReader = new InputStreamReader(fin); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); StringBuilder sb = new StringBuilder(); data = bufferedReader.readLine(); sb.append(data); Log.i("READ", "" + data); } catch (IOException e1) { e1.printStackTrace(); } Log.i("DATA", "" + data); try { if (bundle != null) { final Object[] pdusObj = (Object[]) bundle.get("pdus"); format = intent.getStringExtra("format"); SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[0]); String phoneNumber = currentMessage.getDisplayOriginatingAddress(); String senderNum = phoneNumber; message = currentMessage.getDisplayMessageBody(); Log.i("SmsReceiver", "senderNum: " + senderNum + "; message: " + message); // Show Alert if (message.equalsIgnoreCase(data)) { Intent pop = new Intent(context, PopUp.class); pop.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(pop); } } // bundle is null } catch (Exception e) { Log.e("SmsReceiver", "Exception smsReceiver" + e); } }
public void saveLkedNewsId(JSONArray array) throws JSONException, IOException { Writer writer = null; try { OutputStream out = mContext.openFileOutput(mFilename, Context.MODE_PRIVATE); writer = new OutputStreamWriter(out); writer.write(array.toString()); } finally { if (writer != null) writer.close(); } }
public void savePresidents(List<President> presidents, Context context) { try { FileOutputStream fos = context.openFileOutput("Presidents", Context.MODE_PRIVATE); ObjectOutputStream os = new ObjectOutputStream(fos); os.writeObject(presidents); os.close(); } catch (Exception e) { e.printStackTrace(); } }
private void writeToFile(String data, Context context) { try { OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput(filename, Context.MODE_PRIVATE)); outputStreamWriter.write(data); outputStreamWriter.close(); } catch (IOException e) { Log.e("Exception", "File write failed: " + e.toString()); } }
/** * 保存文件 * * @param filename 文件名称 * @param filecontent 文件内容 */ public void save(String filename, String filecontent) throws Exception { // 私有操作模式:创建出来的文件只能被本应用访问,其它应用无法访问该文件 // 另外采用私有操作模式创建的文件,写入文件中的内容会覆盖源文件的内�? // FileOutputStream outStream = context.openFileOutput(filename, Context.MODE_PRIVATE); FileOutputStream outStream = context.openFileOutput( filename, Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE); outStream.write(filecontent.getBytes()); outStream.close(); }
public void saveNews(Context context) { Log.d( "Unit5Calendar", "Saving News.. We need to not let the user exterminate the app while saving.."); // TODO: // figure // out how // to not // let the // app be // closed // while // saving. try { if (newsFile == null) newsFile = new File(context.getFilesDir(), NEWS_FILE_NAME); if (!newsFile.exists()) newsFile.createNewFile(); BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(context.openFileOutput(NEWS_FILE_NAME, Context.MODE_PRIVATE))); Collections.sort(newsArticles, Utils.articlePubDateSorter); writer.write("size-" + newsArticles.size()); Log.d("NewsSave", "size-" + newsArticles.size()); writer.newLine(); for (Article article : newsArticles) { writer.write(START_ARTICLE); writer.newLine(); if (article.hasPubDate()) { writer.write("pubDate:" + article.getPubDate()); Log.d("NewsSave", "pubDate:" + article.getPubDate()); writer.newLine(); writer.write(NEXT); Log.d("NewsSave", NEXT); writer.newLine(); } writer.write("title:" + article.getTitle()); Log.d("NewsSave", "title:" + article.getTitle()); writer.newLine(); writer.write(NEXT); Log.d("NewsSave", NEXT); writer.newLine(); writer.write("desc:" + article.getDescription()); Log.d("NewsSave", "desc:" + article.getDescription()); writer.newLine(); writer.write(NEXT); Log.d("NewsSave", NEXT); writer.newLine(); } writer.write(END_ARTICLES); Log.d("NewsSave", END_ARTICLES); } catch (IOException e) { Log.d("Unit5Calendar", e.getMessage(), e); } Log.d("Unit5Calendar", "Done saving News, user can now safely exterminate app."); }
@Override public InputStream getPropertiesInputStream(String resourceName) { InputStream in = super.getPropertiesInputStream(resourceName); boolean available = false; try { if (in != null && in.available() > 0) { available = true; } } catch (IOException e) { available = false; } String file = this.getBackupFilename(resourceName); if (available) { try { FileOutputStream out = context.openFileOutput(file, Context.MODE_PRIVATE); Log.d(TAG, "Copying content of " + resourceName + " to backup file " + file); OutputStreamWriter writer = new OutputStreamWriter(out); BufferedWriter bwriter = new BufferedWriter(writer); InputStreamReader reader = new InputStreamReader(in); BufferedReader breader = new BufferedReader(reader); String line = null; try { do { line = breader.readLine(); if (line != null) bwriter.write(line + "\n"); } while (line != null); breader.close(); reader.close(); in.close(); bwriter.close(); writer.close(); out.close(); } catch (IOException e) { Log.e(TAG, "Could not copy the data to backup file: " + e.getMessage(), e); } } catch (FileNotFoundException e) { Log.e(TAG, "Could not create backup file " + file + ": " + e.getMessage(), e); } } else Log.w(TAG, "URL is not available: " + resourceName); try { in = context.openFileInput(file); } catch (FileNotFoundException e) { Log.e(TAG, "URL not available and no backup file - returning null"); in = null; } return in; }